简体   繁体   English

C#退出NetworkStream.read()

[英]c# exit NetworkStream.read()

I have created a TCP listener to receive data from a port. 我创建了一个TCP侦听器来从端口接收数据。 And I created a NetworkStream to read the coming data. 我创建了一个NetworkStream来读取即将到来的数据。

NetworkStream stream = new NetworkStream(TCPSocket);
Byte[] bytes = new Byte[128];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
     string msg = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
     Console.WriteLine("received: {0}", msg);
}

What I want to do is, if there is no data coming for 10 minutes, I want to close the stream. 我想做的是,如果10分钟内没有数据,我想关闭流。 How can I do this? 我怎样才能做到这一点? I have tried to use timer with creating a thread to call stream.close() after sometime, but nothing worked before it receive any data. 我试图在某个时间后使用计时器创建线程来调用stream.close(),但是在接收任何数据之前没有任何作用。 Thanks in advance! 提前致谢!

Try using: 尝试使用:

stream.ReadTimeOut = 600000; 

it is in milliseconds. 以毫秒为单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM