How to use the buffer on SocketAsyncEventArgs object

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-03-21T14:17:07Z Indexed on 2010/03/21 14:21 UTC
Read the original article Hit count: 614

Filed under:
|

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);
            }
        }
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about sockets