tags:

views:

137

answers:

1

Hi:

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_SIZE];

        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

+1  A: 

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).

FacticiusVir