TcpClient.BeginRead Method collision using asynchronous Callbacks

141 Views Asked by At

I am trying to create a Tcp socket server that accepts multiple clients. However, for the past couple of days, I haven't been able to overcome a certain obstacle. I believe I've isolated the problem to be in the TcpClient.BeginRead(callbackMethod) Method.

Basically, distinct clients activate this method but the callback isn't invoked/triggered until they actually send data into their outgoing stream. However, the encoding.ASCII.Getstring() Method I perform on the bytes that come in via the stream outputs an unwanted "0/0/0/" depending on the order the beginread methods were started. Why is this happening? Why? Please help.

The Situation/Scenario in Order

Event 1.) ClientOne Connects which then triggers a BeginRead with asynchronous call back.(Now callback is waiting for data)

Event 2.) ClientTwo Connects which then triggers a BeginRead with asynchronous call back. (Now callback is waiting for data)

Event 3.) If ClientOne sends a message first, the data definitely is serviced, however, the Encoding.ASCII.GetString(3 arguments) outputs "0/" for every byte. I think ClientTwo's BeginRead is interfering with ClientOne's BeginRead somehow.

Event 3. (Not 4)) If ClientTwo sends a message first, the data is serviced and decoded/stringified correctly using Encoding.ASCII.GetString(3 arguments).

Source Code

void onCompleteAcceptTcpClient(IAsyncResult iar){TcpListener tcpl = (TcpListener)iar.AsyncState;
        try
        {
            mTCPClient = tcpl.EndAcceptTcpClient(iar);
            var ClientEndPoint = mTCPClient.Client.RemoteEndPoint;
            Console.log(ClientEndPoint.ToString());

            Console.log("Client Connected...");

            _sockets.Add(mTCPClient);

            tcpl.BeginAcceptTcpClient(onCompleteAcceptTcpClient, tcpl); 

            mRx = new byte[512]; 

            _sockets.Last().GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, mTCPClient);

        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    void **onCompleteReadFromTCPClientStream**(IAsyncResult iar)
    {
        foreach (string message in messages)//For Testing previous saved messages
        {
            printLine("Checking previous saved messages: " + message); 
        }

        TcpClient tcpc = new TcpClient();
        int nCountReadBytes = 0;

        try
        {
            tcpc = (TcpClient)iar.AsyncState;
            nCountReadBytes = tcpc.GetStream().EndRead(iar);
            printLine(nCountReadBytes.GetType().ToString());

            if (nCountReadBytes == 0)
            {
                MessageBox.Show("Client disconnected.");
                return;
            }

            string foo;

         /*THE ENCODING OUTPUTS "0/" FOR EVERY BYTE WHEN AN OLDER CALLBACK'S DATA IS DECODED*/
            foo = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes);
            messages.Add(foo);

            foreach (string message in messages)
            {
                console.log(message); 
            }

            mRx = new byte[512];

           //(reopens the callback)
            tcpc.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, tcpc);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
0

There are 0 best solutions below