我有一些非常简单的代码,可以从它连接的网络流中读取代码行。在代码示例中,每次读取只有一行,并且不会继续从服务器获取更多内容。
怎么啦?
byte[] readBuffer = new byte[1024];
byte[] tempBuff = new byte[1024];
int tempBuffSize = 0;
private void btnConnect_Click(object sender, EventArgs e)
{
TcpClient tcpClient = new TcpClient("192.168.1.151", 5505);
NetworkStream stream = tcpClient.GetStream();
stream.BeginRead(readBuffer, 0, 1024, readHandler, tcpClient);
}
void readHandler(IAsyncResult result)
{
TcpClient tcpClient = (TcpClient)result.AsyncState;
int dataLen = tcpClient.GetStream().EndRead(result);
int currStart = 0;
int currEnd = -1;
for (int i = 0; i < dataLen; i++)
{
if (readBuffer[i] == '\r' && i < (readBuffer.Length - 1) &&
readBuffer[i + 1] == '\n')
{
// Set the end of the data
currEnd = i - 1;
// If we have left overs from previous runs:
if (tempBuffSize != 0)
{
byte[] joinedData = new byte[tempBuffSize + (currEnd - currStart + 1)];
Array.Copy(tempBuff, 0, joinedData, 0, tempBuffSize);
Array.Copy(readBuffer, currStart, joinedData, tempBuffSize, (currEnd - currStart + 1));
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(joinedData);
System.Diagnostics.Debug.Write(myString);
tempBuffSize = 0;
}
else
{
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(readBuffer);
System.Diagnostics.Debug.Write(myString);
// HandleData(readBuffer, currStart, currEnd);
}
// Set the new start - after our delimiter
currStart = i + 2;
}
}
// See if we still have any leftovers
if (currStart < dataLen)
{
Array.Copy(readBuffer, currStart, tempBuff, 0, dataLen - currStart);
tempBuffSize = dataLen - currStart;
}
} 发布于 2011-08-24 19:39:56
为什么你一开始就希望它能读取全部信息?我不是专家,但在我看来,同步或异步方法都不能保证读取所有数据(无论这意味着什么,因为只要套接字打开,就会有更多数据到达)。在EndRead方法中的代码之后,如果需要更多数据,应该再次调用Read或BeginRead。您应该知道,根据您与客户端建立的协议,是否需要更多数据。
发布于 2011-08-24 19:29:35
在为嵌入式设备开发tcp应用程序时,我也遇到过类似的问题。在我的例子中,问题是设备在延迟的时间内发出数据,因此在其余数据进入之前,控制移动到程序的下一行,只从服务器获取初始数据。我通过引入延迟来解决这个问题。
紧跟在您从服务器读取数据的行后引入了一个延迟,因此最好在单独的线程上运行它
thread.sleep(3000)这很可能是你的问题。
发布于 2011-08-24 19:17:52
也许你的流对象在它超出作用域的时候,在readHandler被再次调用之前就被释放了。尝试将tcpClient和流提升到类作用域而不是方法作用域,或者将读取移动到操作完成时退出的单独线程。
https://stackoverflow.com/questions/7174526
复制相似问题