tags:

views:

66

answers:

2

I am receiving 3144 bytes of data through TCP/IP socket during debug mode, but in excecution 1023 bytes were received. Why isn't the remaining data read?

IPEndPoint ipEnd = new IPEndPoint(ipAdd, ipPort);
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soc.Connect(ipEnd);
byte[] sendData = Encoding.ASCII.GetBytes("msg");
soc.Send(sendData);
int byteLen = 4*1024;
byte[] RecData = new byte[byteLen];
int DataLen = soc.Receive(RecData, 0, RecData.Length, SocketFlags.None);// Here I placed breakpoint

string str = Encoding.ASCII.GetString(RecData, 0, DataLen);
MessageBox.WriteLine(str);
soc.Close();

On step by step debug I get DataLen as 3144 bytes and it works properly. During excecution, though, I am receiving DataLen as 1023 bytes. Why does this happen? I need to print the received data str in either a MessageBox or TextBox.

+3  A: 

You seem to be assuming that you'll receive all the data in a single Receive call. TCP/IP is a streaming protocol - you shouldn't make that assumption.

You need to loop round, reading as much data as is appropriate. Ideally, your protocol should tell you how data to read as part of each "message" (or whatever your equivalent concept is) or close the socket when it's finished writing. In either of those situations, you'll know when you've read everything. The alternative is to include a delimiter, which means you'll still know when you've read a complete "message" - but you'll also have potentially read the start of the next message.

Jon Skeet
A: 

You should receive parts of data in a loop, until you get it all.
Take a look a the code below:

void Receive(Socket socket, byte[] buffer, int offset, int size)
{
  int received = 0;  
  do {
    try {
      received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
    }
  } while (received < size);
}
Andrew
Good! It works fine.
Praveen Raj V
How would the available bytes in the socket could be found without using "socket.Available".
Praveen Raj V