确保StreamReader的不挂等待数据不挂、数据、StreamReader

由网友(自此不见)分享简介:在code以下读取一切有从TCP客户端流中读取,并在接下来的迭代它只是坐在那里读()(我假设等待数据)。我怎样才能确保它不会,只是返回的时候有什么也没有读什么书?我一定要设置为低超时,当它失败了回应一个例外?还是有更好的办法?TcpClient的tcpclnt =新的TcpClient();tcpclnt.Conne...

在code以下读取一切有从TCP客户端流中读取,并在接下来的迭代它只是坐在那里读()(我假设等待数据)。我怎样才能确保它不会,只是返回的时候有什么也没有读什么书?我一定要设置为低超时,当它失败了回应一个例外?还是有更好的办法?

  TcpClient的tcpclnt =新的TcpClient();
tcpclnt.Connect(IP,端口);

流STM = tcpclnt.GetStream();

stm.Write(cmdBuffer,0,cmdBuffer.Length);

byte []的响应=新的字节[2048];

MemoryStream的毫秒=新的MemoryStream();
byte []的缓冲区=新的字节[2048];
INT长;
而((长度= stm.Read(缓冲液,0,buffer.Length))大于0)
    ms.Write(缓冲液,0,长度);

byte []的响应= ms.ToArray();


tcpclnt.Close();
 

解决方案

也许你应该使用多线程。一个线程要等待数据,另一个应该处理接收到的数据。

The code below reads everything there is to read from tcp client stream, and on the next iteration it will just sit there on the Read() (i'm assuming waiting for data). How can I ensure it doesn't and just returns when there's nothing there to read? Do I have to set low timeout, and respond to an exception when it fails out? Or there's a better way?

TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);

Stream stm = tcpclnt.GetStream();

stm.Write(cmdBuffer, 0, cmdBuffer.Length);

byte[] response = new Byte[2048];

MemoryStream ms = new MemoryStream();
byte[] buffer = new Byte[2048];
int length;
while ((length = stm.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, length);

byte[] response = ms.ToArray();


tcpclnt.Close();
动静有数 史上最热黄金周 来了, 五一去哪玩 搜索暴涨203

解决方案

Maybe you should use multithreading. One thread should wait for data, another should process received data.

阅读全文

相关推荐

最新文章