[Q] Receiving asynchron datas with Sockets

  • Thread starter =?ISO-8859-1?Q?Andr=E9_Betz?=
  • Start date
?

=?ISO-8859-1?Q?Andr=E9_Betz?=

Hi,

I've established a TCP-Socket Connection and now I want to receive
datas. So I called BeginReceive where I set the receiving buffer and
length. Now in the asynchronous CallBack-Function I call EndReceive and
get the length of rceived datas. After receiving datas I call the
Beginreceive-Function again.

So my question is now what is if the send datas is greater than the
receiving buffer? Ok, I know, I will get it in the next receiving round
but how do I now that the received datas belong together and doesn't
belong to the next sending-session from the connected socket?

Thanks
 
G

Guest

Hi, You need to use the state object and look for a terminating string/value.
Here is an example.

private void RecieveCallback(IAsyncResult ar)
{
if((int)this.listener.Handle > 0)
{
string socketData = string.Empty;

SocketState state = (SocketState)ar.AsyncState;
Socket handler = state.serviceSocket;

// Add connection to client list
//this.clientConnections.Add(state);

int bytesRead = handler.EndReceive(ar);

if(bytesRead > 0)

state.stringBuffer.Append(Encoding.ASCII.GetString(state.byteBuffer,0,bytesRead));
socketData = state.stringBuffer.ToString();

if(socketData.IndexOf(Encoding.ASCII.GetString(eof))> -1)

handler.BeginSend(Encoding.ASCII.GetBytes(socketData),0,socketData.Length,SocketFlags.None, new AsyncCallback(SendCallback),state);
}
else

handler.BeginReceive(state.byteBuffer,0,state.bufferSize,SocketFlags.None,new AsyncCallback(RecieveCallback),state);
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top