AsyncState 始终为空套接字编程多客户端服务器



我正在尝试创建一个可以处理多个客户端的服务器,我能够连接多个客户端,但是一旦发送一些东西,我就会收到错误"System.NullReferenceException:"对象引用未设置为对象的实例。ReceiveCallBack 中的 AsyncState 始终为空。

private void AcceptCallBack(IAsyncResult AR)
{
    try
    {

    Socket c; c = _s.EndAccept(AR);
        clients.Add(c);
        if (richTextBox1.InvokeRequired)
            richTextBox1.Invoke(new Action(() => richTextBox1.Text += "Client Connected: " + c.RemoteEndPoint + "rn"));
        else
            richTextBox1.Text += c.RemoteEndPoint + "rn";
        _data = new byte[c.ReceiveBufferSize];
        c.BeginReceive(_data, 0, _data.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
        _s.BeginAccept(new AsyncCallback(AcceptCallBack), null);
    }
    catch (Exception e)
    {
        MessageBox.Show("An error AcceptCallBack.");
    }
}
private void ReceiveCallBack(IAsyncResult AR)
{
    try
    {
        //Socket s = c;
        var s = (Socket) AR.AsyncState;
        var rec = s.EndReceive(AR);
        var thread = new Thread(new ThreadStart(() => ReceiveData(rec)));
        thread.Start();
        s.BeginReceive(_data, 0, _data.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
    }
    catch (SocketException e)
    {
        MessageBox.Show(e.ToString());
    }
}
private void ReceiveData(int rec)
{
    var data = Encoding.ASCII.GetString(_data, 0, rec);
    Append(data);
}
private void Append(string data)
{
    var invoker = new MethodInvoker(delegate
    {
        richTextBox1.Text += data + "rn";
    });
    Invoke(invoker);
}

正如@Jeoroem在注释中所说,我必须将套接字传递给BeginReceive。

最新更新