0

我正在尝试创建一个接受多个客户端的 Tcp 套接字服务器。但是,在过去的几天里,我一直无法克服某些障碍。我相信我已经将问题隔离在 TcpClient.BeginRead( callbackMethod ) 方法中。

基本上,不同的客户端会激活此方法,但不会调用/触发回调,直到它们实际将数据发送到其传出流中。但是,我对通过流传入的字节执行的 encoding.ASCII.Getstring() 方法会输出不需要的“0/0/0/”,具体取决于 beginread 方法的启动顺序。为什么会这样?为什么?请帮忙。

有序的情况/情景

事件 1.) ClientOne Connects 然后触发 BeginRead 异步回调。(现在回调正在等待数据)

事件 2.) ClientTwo 连接,然后触发带有异步回调的 BeginRead。(现在回调正在等待数据)

事件 3.)如果 ClientOne 先发送消息,则数据肯定会得到服务,但是 Encoding.ASCII.GetString(3 arguments) 会为每个字节输出“0/”。我认为 ClientTwo 的 BeginRead 以某种方式干扰了 ClientOne 的 BeginRead。

事件 3。(不是 4))如果 ClientTwo 先发送消息,则使用 E​​ncoding.ASCII.GetString(3 个参数)正确处理和解码/字符串化数据。

源代码

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

0 回答 0