/// <summary> /// This is mentioned to be a core for when a new message arrives from a client /// but make a simplier version where we read an opcode, data and send in a structured data /// the socket who's doing this /// </summary> /// <param name="ar"></param> private void OnClientMessage(IAsyncResult ar) { var handler = (NetworkClient)ar.AsyncState; if (handler == null) { Debug.Warning("We got a null handler at OnClientMessage. Handle this!"); } try { SocketError error; int read = handler.Socket.EndReceive(ar, out error); if (error != SocketError.Success) { //This means a socket has disconnected if (error == SocketError.ConnectionReset) { var netMsg = new NetworkMessage(handler, null); NotifyDisconnection(netMsg); return; } } else if (error == SocketError.Success) { if (read > 0) { //Extract json data var encodedBytes = Encoding.UTF8.GetString(handler.buffer); var packet = JPacketBuilder.Deserialize <Packet>(encodedBytes); var msg = new NetworkMessage(handler, packet.data); //Notify the callbacks waiting for this opcode NotifyDataReceived(packet.opcode, msg); //Clear the buffer handler.ClearBuffer(); //Return getting more handler.Socket.BeginReceive(handler.buffer, 0, handler.buffer.Length, 0, new AsyncCallback(OnClientMessage), handler); } else { if (handler.IsConnected()) { handler.Socket.Disconnect(false); } var netMsg = new NetworkMessage(handler, null); NotifyDisconnection(netMsg); } } } catch (Exception e) { // Handle all other exceptions Console.WriteLine(e.ToString()); if (handler.IsConnected()) { handler.Socket.Disconnect(false); } var netMsg = new NetworkMessage(handler, null); NotifyDisconnection(netMsg); } }
/// <summary> /// Subscribed event for disconnection detect /// </summary> /// <param name="client"></param> private void OnClientDisconnect(NetworkMessage netMsg) { netMsg.Sender.Socket.Close(); this._connectedSockets.Remove(netMsg.Sender); }