c# exit NetworkStream.read()

本文关键字:read NetworkStream exit | 更新日期: 2023-09-27 18:02:47

我已经创建了一个TCP侦听器来接收来自端口的数据。我创建了一个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);
}

我想做的是,如果10分钟内没有数据来,我想关闭流。我该怎么做呢?我曾尝试使用计时器创建一个线程,在一段时间后调用stream.close(),但在它接收任何数据之前没有任何工作。提前感谢!

c# exit NetworkStream.read()

尝试使用:

stream.ReadTimeOut = 600000; 

以毫秒为单位。