0

I am trying to create a server that can handle multiple clients, I am able to connect multiple clients but as soon as send something I get an error "System.NullReferenceException: 'Object reference not set to an instance of an object.'", now this is because my AR.AsyncState in ReceiveCallBack is always null.

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 + "\r\n"));
        else
            richTextBox1.Text += c.RemoteEndPoint + "\r\n";
        _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 + "\r\n";
    });
    Invoke(invoker);
}
Danial Ahmed
  • 856
  • 1
  • 10
  • 26
  • `AsyncState` is what you pass as the last parameter to the `Begin...` method -- and as you're passing `null`, that's exactly what you get. Pass the socket instead. (Better yet, start using `async` / `await` instead of old-style async programming for code that's much easier to understand.) – Jeroen Mostert Nov 20 '19 at 18:32

1 Answers1

0

as @Jeoroem said in comment instead of passing null I had to pass socket to BeginReceive.

Danial Ahmed
  • 856
  • 1
  • 10
  • 26