/// <summary> /// Sends data to a specific group of connected users /// </summary> /// <param name="group"></param> /// <param name="opcode"></param> /// <param name="obj"></param> public void SendToGroup(List <NetworkClient> clients, short opcode, object obj) { if (clients.Count > 0) { lock (clients) { foreach (var client in clients) { if (client.IsConnected()) { //Create a internal data structure var packet = new Packet { opcode = opcode, data = JPacketBuilder.Serialize(obj) }; //Serialize all the packet data var payload = JPacketBuilder.Serialize(packet); //Now convert to a buffer byte byte[] byteData = Encoding.ASCII.GetBytes(payload); Console.WriteLine($"Sending {byteData.Length} bytes to the client id " + client.connectionId); // Begin sending the data to the remote device. client.Socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } } } } }
/// <summary> /// Sends data to all the connected sockets /// </summary> /// <param name="opcode"></param> /// <param name="obj"></param> public void SendToAll(short opcode, object obj) { for (var i = 0; i < this._connectedSockets.Count; i++) { var user = this._connectedSockets[i]; if (user.IsConnected()) { //Create a internal data structure var packet = new Packet { opcode = opcode, data = JPacketBuilder.Serialize(obj) }; //Serialize all the packet data var payload = JPacketBuilder.Serialize(packet); //Now convert to a buffer byte byte[] byteData = Encoding.ASCII.GetBytes(payload); Console.WriteLine($"Sending {byteData.Length} bytes to the client id " + user.connectionId); // Begin sending the data to the remote device. user.Socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), user); } } }
/// <summary> /// Sends an object with an opcode identifier to the remote server /// </summary> /// <param name="opcode"></param> /// <param name="data"></param> public void Send(short opcode, object data) { if (!this.Connection.IsConnected()) { return; } //Create a internal data structure var packet = new Packet { opcode = opcode, data = JPacketBuilder.Serialize(data) }; //Serialize all the packet data var payload = JPacketBuilder.Serialize(packet); Debug.Log("Payload = " + payload); //Now convert to a buffer byte byte[] byteData = Encoding.ASCII.GetBytes(payload); Debug.Log($"Sending {byteData.Length} bytes to the server"); // Begin sending the data to the remote device. this.Client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), this.Client); }
/// <summary> /// Internal callback to handle data receive /// </summary> /// <param name="ar"></param> private void OnDataReceive(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. var handler = (NetworkConnection)ar.AsyncState; var client = handler.socket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. var encodedBytes = Encoding.ASCII.GetString(handler.buffer, 0, bytesRead); Debug.Log("Data received : " + encodedBytes); var packet = JPacketBuilder.Deserialize <Packet>(encodedBytes); var netMsg = new NetworkMessage(handler, packet.data); //Notify the callbacks waiting for this opcode NotifyDataReceived(packet.opcode, netMsg); // Get the rest of the data. client.BeginReceive(handler.buffer, 0, handler.buffer.Length, 0, new AsyncCallback(OnDataReceive), handler); } } catch (Exception e) { NotifyDisconnection(new NetworkMessage(null, null)); } }
/// <summary> /// Reads a serialized stream message /// </summary> /// <typeparam name="TMsg"></typeparam> /// <returns></returns> public TMsg ReadMessage <TMsg>() { if (!String.IsNullOrWhiteSpace(this.jdata)) { return(JPacketBuilder.Deserialize <TMsg>(this.jdata)); } else { return(default(TMsg)); } }
/// <summary> /// Reads a serialized stream message /// </summary> /// <typeparam name="TMsg"></typeparam> /// <returns></returns> public TMsg ReadMessage <TMsg>() { //Since we are dealing with json packets lets be sure //we saved a json string if (this.jdata.GetType() != typeof(String)) { return(default(TMsg)); } //Is the string ok? if (!String.IsNullOrWhiteSpace(this.jdata)) { return(JPacketBuilder.Deserialize <TMsg>(this.jdata)); } else { return(default(TMsg)); } }
/// <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); } }