private void ReceiveCallback(IAsyncResult result) { var currentResult = (result.AsyncState as KeyValuePair <int, Socket>?).GetValueOrDefault(); int received = -1; try { received = currentResult.Value.EndReceive(result); } catch (SocketException) { } var currentUser = GetUser(currentResult.Key); var currentSocket = currentResult.Value; if (received == -1) { currentSocket.Shutdown(SocketShutdown.Both); ConnectedClients.RemoveAll(c => c.Socket.Equals(currentResult.Value)); ClientDisconnected?.Invoke(this, currentUser); _serverSocket.BeginAccept(AcceptCallback, null); return; } byte[] recBuf = new byte[received]; Array.Copy(_buffer, recBuf, received); if (Received != null) { var responsePacket = new ResponsePacket(); try { var sentPacket = WrappedPacket.FromJson(Encoding.UTF8.GetString(recBuf)).GetPacket(); responsePacket.SentPacketData = JToken.FromObject(sentPacket); responsePacket.SentPacketType = sentPacket.GetType().ToString(); } catch { responsePacket.SentPacketData = JToken.FromObject(new { content = Encoding.UTF8.GetString(recBuf) }); responsePacket.SentPacketType = typeof(JToken).ToString(); } responsePacket.Accepted = Received.Invoke(this, currentUser, recBuf); var wrappedPacket = new WrappedPacket() { PacketType = responsePacket.GetType().ToString(), PacketData = JObject.FromObject(responsePacket) }; currentResult.Value.Send(Encoding.UTF8.GetBytes(JObject.FromObject(wrappedPacket).ToString())); } currentResult.Value.BeginReceive(_buffer, 0, _bufferSize, SocketFlags.None, ReceiveCallback, currentResult); }