J.Chen J.Chen - 3 months ago 25
C# Question

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!

Answer

Try using:

stream.ReadTimeOut = 600000; 

it is in milliseconds.

Comments