A few days back I was just coding for a basic TCP/IP Client to send and
recieve buffer across network.
I encountered a problem in receiving data through receive method.
I am sharing this with community as it may help others, who are novice is
..NET socket programming.
I searched all over net for samples and found all over (including MSDN).
Blocking mode was enough for me so I coded my receive as:
<CODE>
Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
</CODE>
But later I noticed that if in last iteration the bytes come to be less than
256 i.e. when I have received all data the next receive call causes the
execution to block as receive has nothing to receive.
Realizing that I changed my code to:
<CODE>
Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes != 256);
</CODE>
It worked fine for all my real scenarios. But I kept thinking that it will
also cause problem if the bytes to be received is multiple of 256 chunks. In
that case it will also block execution when last time it calls receives
method.
Finally I got something better:
<CODE>
Byte[] bytesReceived = new Byte[256];
while (s.Available)
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
</CODE>
I thought it would be appropriate to change my do-while loop to while. But I
did a mistake there. As sometimes s.Available returns 0 even if receive is
able to receive data. And so in all such cases my loop to recieve data got
bypassed.
As I analyzed this and guessed reason was the data chunk was not available
when s.Available is called but since receive is a blocking call it waits for
data arrival and finally returns with data.
So, finally I changed the code to following and it worked fine.
<CODE>
Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (s.Available);
</CODE>
Regards,
Rahul Anand