简体   繁体   中英

c# exit NetworkStream.read()

I have created a TCP listener to receive data from a port. And I created a NetworkStream to read the coming data.

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. 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. Thanks in advance!

Try using:

stream.ReadTimeOut = 600000; 

it is in milliseconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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