C#服务器端只能一次接收来自客户端的消息。 (插座)

时间:2018-08-09 06:53:54

标签: multithreading sockets server communication

我使用下面的代码从客户端接收ReceiveCallBack。我不知道此代码部分的问题是什么导致我的函数仅从客户端接收消息一次。

    public void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Fetch a user-defined object that contains information 
            object[] obj = new object[2];
            obj = (object[])ar.AsyncState;

            // Received byte array 
            byte[] buffer = (byte[])obj[0];

            // A Socket to handle remote host communication. 
            handler = (Socket)obj[1];

            // Received message 
            string content = string.Empty;


            // The number of bytes received. 
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                content += Encoding.Unicode.GetString(buffer, 0,
                    bytesRead);

                // If message contains "<Client Quit>", finish receiving
                if (content.IndexOf("<Client Quit>") > -1)
                {
                    //Control.CheckForIllegalCrossThreadCalls = false;
                    // Convert byte array to string
                    string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));

                   MsgToReceived(content);    

                }
                else
                {
                    // Continues to asynchronously receive data
                    byte[] buffernew = new byte[1024];
                    obj[0] = buffernew;
                    obj[1] = handler;
                    handler.BeginReceive(buffernew, 0, buffernew.Length,
                        SocketFlags.None,
                        new AsyncCallback(ReceiveCallback), obj);
                }
            }
        }
        catch (Exception exc) { MessageBox.Show(exc.ToString()); }
    }

以下代码用于解决跨线程错误

    private void MsgToReceived(string content)
    {
        if (this.InvokeRequired)
            this.Invoke(new updatetbMsgReceived(this.MsgToReceived), content);
        else
            tbMsgReceived.Text = content;
    }

0 个答案:

没有答案