【发布时间】:2009-03-03 22:20:08
【问题描述】:
我使用Socket 通过 TCP 接收数据,并使用TextReader.ReadLine 从连接中读取行。存在未收到完整行的问题——TextReader.ReadLine 返回不完整的字符串。我希望它返回null,表示无法读取整行。我该怎么做?
基本上,我有这个数据传入:
"hello\nworld\nthis is a test\n"
当我运行ReadLine 时,我会得到这些回报:
"hello"
"world"
"this is a te"
<null>
<socket gets more data>
"st"
<null>
我不想返回“this is a te”。相反,我希望“这是一个测试”等到收到整行。
代码:
var endPoint = ...;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(endPoint);
var stream = new NetworkStream(socket, true);
var messageBuffer = new StringBuilder();
// Data received async callback (called several times).
int bytesRead = stream.EndRead(result);
string data = Encoding.UTF8.GetString(readBuffer.Take(bytesRead).ToArray());
messageBuffer.Append(data);
using(var reader = new StringReader(messageBuffer.ToString()))
{
// This loop does not know that Message.Read reads lines. For all it knows, it could read bytes or words or the whole stream.
while((Message msg = Message.Read(reader)) != null) // See below.
{
Console.WriteLine(msg.ToString()); // See example input/echo above.
}
messageBuffer = new StringBuilder(reader.ReadToEnd());
}
// Method of Message.
public static Message Read(TextReader reader)
{
string line = reader.ReadLine();
if(line == null)
return null;
return Message.FromRawString(line);
}
谢谢。
【问题讨论】:
-
真的需要看你的代码,看看你是如何配置socket和TextReader的。
-
@Richard,它抽象了很多,但我会尝试提取必要的部分。
标签: c# networking