In my socket-application I want about 80-100 clients to be connected to my server simultaneously.
Here the socket.BeginAccept part of my server:
try
{
_serverSocket.Bind(localEndPoint);
_serverSocket.Listen(100);
while (maintainActiveSocket)
{
_serverSocket.BeginAccept(new AsyncCallback(Accept), _serverSocket);
clientAccepted.WaitOne();
}
}
So as soon as one of my clients tries to connect to the server this is called, it checks if this client is already known and if not adds him to a ConcurrentDictionary, after it starts socket.BeginReceive to constantly try to receive in a while-loop for as long as this socket is connected. This while-loop throws a NullReferenceException the second time it receives data. The acceptedClient.sCom.Buffer should be byte[2048] but the second time it receives data it is null. Why is this and how can I fix it?
Socket socket = _serverSocket.EndAccept(ar);
clientAccepted.Set();
_Client acceptedClient = new _Client();
if (!Dict.connectedClients.Any((a) => a.Value.Socket == socket))
{
acceptedClient.Socket = socket;
Dict.connectedClients.TryAdd(getFirstKey(), acceptedClient);
}
acceptedClient = Dict.connectedClients.Single((a) => a.Value.Socket == socket).Value;
while (socket.Connected)
{
socket.BeginReceive(
acceptedClient.sCom.Buffer, 0, acceptedClient.sCom.Buffer.Length, 0,
new AsyncCallback(Receive), acceptedClient);
receiveDone.WaitOne();
}
As soon as the socket starts receiving this is finally called:
private static void Receive(IAsyncResult ar)
{
_Client client = (_Client)ar.AsyncState;
Logger.Instance.Log("Receiving on " + client.Socket.Handle);
int bytesRead = client.Socket.EndReceive(ar);
Logger.Instance.Log("received " + bytesRead.ToString());
for (int i = 0; i < bytesRead; i++)
{
client.sCom.TransmissionBuffer.Add(client.sCom.Buffer[i]);
client.sCom = client.sCom.DeSerialize();
Logger.Instance.Log("name: " + client.Clientname);
receiveDone.Set();
}
}
The received data is previously buffered in sCom.Buffer which is a byte[2048]. It is then copied to sCom.TransmissionBuffer which is a List and is deserialized afterwards.
I don't understand why the Buffer in my second code-block is null after working fine for the first iteration of the loop.