Search code examples
c#socketsseparator

Is there a way to introduce a separator in socket reception?


I'm working with C# socket communication, and I receive different messages, separated by a special character (ASCII code 3).

Currently this is not taken into account and my setup of the reception, who looks as follows:

sock.BeginReceive(_receivedData, 
                  0, 
                  _receivedData.Length, 
                  SocketFlags.None, 
                  OnReceivedData, 
                  sock);

This receives different messages, separated by the mentioned character, as one message.

Inside of the OnReceivedData(...) I can run through the whole received bytearray, and look for that special character myself, but I would prefer having this handled by the socket handler itself.

Does anybody know how to declare the callback receive in order to take a separator into account, something like (pseudo-code):

sock.BeginReceive(_receivedData, 
                  0, 
                  _receivedData.Length, 
                  SocketFlags.None, // maybe here?
                  OnReceivedData, 
                  sock, 
                  separator=chr(3));

Edit after some more investigation

The "complete" code concerning the reception of the data looks as follows:

private void SetupReceiveCallback(Socket sock)
{  try
     { sock.BeginReceive(_receivedData, 0, _receivedData.Length, SocketFlags.None, OnReceivedData, sock);}
   catch (Exception ex)
     { }
}

private void OnReceivedData(IAsyncResult ar)
{  sock = (Socket)ar.AsyncState;

   // Check if we got any data
   try
     {
        int nBytesRec = sock.EndReceive(ar);

This (sock.BeginReceive()takes in a whole bunch of data at once, while I would like the data being taken up to a certain character (0x03), which is the terminator of my message.

My own answer is wrong indeed, as it takes data, which are not even complete, causing a mess (as predicted by Dialectus).
As far as the proposal from Panagiatos: I'm very new at C# programming. How can I do this?

Thanks in advance


Solution

  • As mentioned in the many comments, immediately after having posted the question, a separator cannot be declared in the communication part of my application: I just have to get everything coming from the socket, and do the separation myself, which I did like this:

    string [] infoList = infoString.Split('\u0003');
    foreach (string infoEntry in infoList)
    {
        ... // do the treatment of the messages, one by one