We’re stuck with using buffers on the SocketAsyncEventArgs object.
With the old socket method we’d cast our state object, like this:
clientState cs = (clientState)asyncResult.AsyncState;
However, the 3.5 framework is different.
With have strings arriving from the client in chunks and we can’t seem to work out how the buffers work so we can process an entire string when we find a char3.
Code at the moment:
private void ProcessReceive(SocketAsyncEventArgs e)
{
string content = string.Empty;
// Check if the remote host closed the connection.
if (e.BytesTransferred > 0)
{
if (e.SocketError == SocketError.Success)
{
Socket s = e.UserToken as Socket;
//asyncResult.AsyncState;
Int32 bytesTransferred = e.BytesTransferred;
// Get the message received from the listener.
content += Encoding.ASCII.GetString(
e.Buffer, e.Offset, bytesTransferred);
if (content.IndexOf(Convert.ToString((char)3)) > -1)
{
e.BufferList = null;
// Increment the count of the total bytes receive by the server
Interlocked.Add(ref this.totalBytesRead, bytesTransferred);
}
else
{
content += Encoding.ASCII.GetString(
e.Buffer, e.Offset, bytesTransferred);
ProcessReceive(e);
}
}
else
{
this.CloseClientSocket(e);
}
}
}
I’ll start by saying I’ve never worked with .NET 3.5 sockets, so this answer is a bit of an educated guess.
The problem you are having is that you aren’t storing the content in some state on each read.
So the problems are:
Firstly
You call ProcessReceive:
string content = string.Empty;You append to content: ‘content += Encoding.ASCII.GetString(e.Buffer, e.Offset, ew.BytesTransferred);`
string content = string.Empty;Secondly
To receive the remaining data you are calling ProcessReceive, this is incorrect. You need to issue another read to the underlying Socket using ReceiveAsync.
I’ve modified your code using this blog post.