views:

49

answers:

1

In my program i'm creating socket and whes client connects i'm creating new thread and trying to read and write from/to connected to this socket, but alway get an Read Error because host-computer closed connection for the second command, first command from client worfs fine, and third works fine. i try to check if clientSocket is connected and if networkStream is readable and they alway returns true. how can i solve this? and how can it be - networkStream.CanRead returns true but networkStreamRead raises error? I am new to C# and socket programming so sorry for dumb question.

clientSocket is an TcpClient
networkStream is an NetworkStream

if (clientSocket.Connected == true)
{
   requestCount = requestCount + 1;
   networkStream = clientSocket.GetStream();
   if (networkStream.CanRead == true)
   {
         networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
         dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
   }

}
+2  A: 

The NetworkStream.CanRead property only indicates that the stream supports reading, doesn't mean at all that data is available. When reading from the network you always have to keep reading until an entire frame is complete, where the meaning of the frame is entirely protocol dependent: it could mean a preamble size header, a terminator like \0x0A or a special sequence like a single dot on a line. While the frame is incomplete, you have to keep posting Receive buffers, or read from the stream if using the streaming API.

A second issue is that you obviously have to restrict yourself into interpreting only the bytes you received, not the entire posted buffer. NetworkStream.Read returns the actual number of bytes received available so far, anything after that in the buffer is garbage:

networkStream = clientSocket.GetStream();
int bytesReceived = networkStream.Read(
   bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(
   bytesFrom, 0, bytesReceived);

This still doesn't handle the frame delimiter correctly, since you don't know if the dataFromClient is all the data from client, but that is completely protocol dependent.

Remus Rusanu
+1 for a very good explanation of basic network programming.
Emiswelt