First things first, let me explain my situation: I’m working on a client and a server in C# which use socket for communication.
For practical reason, I use the asynchronous part of both socket to transmit binary serialized objects from the client to the server and vice-versa.
My problem is that when I send too much object at once, the receiver object “stack” into the buffer and when I try to unserialize the buffer content, it give me only one object.
My question is : How can I separate each object from a buffer ?
Here is my ReceiveCallback function :
private void ReceiveMessageCallback(IAsyncResult asyncResult)
{
Socket socket = (Socket)asyncResult.AsyncState;
try
{
int read = socket.EndReceive(asyncResult);
if (read > 0)
{
Log("Reception of " + read + " Bytes");
// Jumper is an object that I use to transport every message
Jumper pod = Common.Serializer.DeSerialize<Jumper>(this.readbuf);
Buffer.SetByte(this.readbuf, 0, 0);
socket.BeginReceive(this.readbuf, 0, this.readbuf.Length, SocketFlags.None, new AsyncCallback(ReceiveMessageCallback), socket);
//We fire an event to externalise the analyse process
Receiver(pod, socket);
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset)
{
socket.Close();
Log("Distant socket closed");
}
else
Log(ex.Message);
}
catch (Exception ex)
{
Log(ex.Message);
}
}
Deserialization will consume your buffer for one object, and will left ‘read pointer’ of the buffer at the start of the next object.
My suggestion would be to either:
or
Second approach will most likely fail because nobody can guarantee that you will always get WHOLE objects in one go, since stream that is attached to a socket is a sequence of bytes, and it can be broken at any point.
Hope that makes some sense.
EDIT:
In fact, the proper thing to do this would be to encapsulate each ‘message’ (serialized object on sending) into a packet, in which for example you’ll have a small header telling you LENGTH of the packet, and upon reception, you will read the socket stream until you have complete packet data, then serialize. And then the next packet, and so on.
EVEN MORE:
Say you send data at a rate of 1000 bytes at the sender side into the socket. On the receiving side, you’ll probably NEVER get 1000 by 1000 bytes out of the socket, in fact you can expect that only under two conditions: