/// <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);
                }
            }
        }
Beispiel #3
0
        /// <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);
            }
        }