I am trying to implement a tcp client listening function. This means that after connection established with server, this tcp client just sit there and waiting for new data to arrive. Here is my code but when it runs, it complain about not been able to read anything from the network stream. But the server hasn't started sending data yet. I guess the complains is because of the timeout in tcp client.
Is this the right way to do it?
public void listen(dataHandler processDataFuc)
{
NetworkStream stream;
Byte[] data_buffer = new Byte[MAX_PACKET_SIZ开发者_StackOverflow社区E];
if(!this.Connected)
{
this.Connect();
}
while (!this.terminate_listening)
{
stream = main_client.GetStream();
while (stream.Read(data_buffer, 0, data_buffer.Length) > 0)
{
processDataFuc(data_buffer);
}
}
}
Thanks
The short answer is yes, it'll do what you want, but it's not ideal. I'd first suggest moving stream = main_client.GetStream();
out of the while
loop, as you're just getting the same stream over and over. Also, using NetworkStream.Read
isn't the best way to perform a continuous read if you're expecting intermittent data over a long period of time, as it's holding up a thread just for that one task; better to use BeginRead
and pass in a callback, which will return immediately but later alert you when data is available (via the callback).
Checkout the methods EstablishConnection() and IncomingDataSyncWorker() (synchronous) or IncomingPacketHandler() (asynchronous) for examples of what you want to do. All these methods are part of networkComms.net an opensource network communication library.
What version of .Net are you using?
If you are using .Net 4.0 or 4.5, then you can use ReadAsync()
instead of Read()
.
Consider this:
public async void listen(dataHandler processDataFuc)
{
NetworkStream stream;
Byte[] data_buffer = new Byte[MAX_PACKET_SIZE];
if(!this.Connected)
this.Connect();
stream = main_client.GetStream();
while (!this.terminate_listening)
{
await stream.ReadAsync(data_buffer, 0, data_buffer.Length)
processDataFuc(data_buffer);
}
}
In such way, ReadAsync()
will waits in a separate Thread until server sends some Data. Then the rest of your code will execute.
精彩评论