Problem in receiving TCP/IP socket data in C#
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
.
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.
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);
}
精彩评论