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