Example #1
0
        public async void ProcessPicture(string file)
        {
            var data = new SendData();

            data.Path = file;
            data.Data = Convert.ToBase64String(System.IO.File.ReadAllBytes(file));

            var j = JsonConvert.SerializeObject(data);
            var c = new StringContent(j);

            c.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            try {
                var answer = await httpClient.PutAsync("http://localhost:5000/main", c);

                data.TypeName = await answer.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(data.TypeName))
                {
                    return;
                }
                queue.Enqueue(data);
                OnProcessedImage?.Invoke();
            }
            catch
            {
                OnConnectionFailed?.Invoke();
            }
        }
 public override void OnConnectionFail(DisconnectCause cause)
 {
     if (OnConnectionFailed != null)
     {
         OnConnectionFailed.Invoke(cause);
     }
 }
Example #3
0
        public void ConnectToServer()
        {
            hubConnection = new HubConnection(serverAddress);
            hubProxy      = hubConnection.CreateHubProxy("SoftNodesHub");
            bool isConnected = false;

            while (!isConnected)
            {
                try
                {
                    hubConnection.Start().Wait();
                    hubConnection.Closed += OnHubConnectionClosed;
                    //hubProxy.On<Message>("ReceiveMessage", ReceiveMessage);

                    isConnected = true;
                    LogInfo("Connected to server");
                    OnConnected?.Invoke();
                }
                catch (Exception e)
                {
                    LogError("Connection to server failed: " + e.Message);
                    OnConnectionFailed?.Invoke(e.Message);
                }
            }
        }
Example #4
0
        public void Send(string value)
        {
            if (!IsConnected())
            {
                return;
            }

            try
            {
                int result = hubProxy.Invoke <int>("SetValue", value, receiverChannel, receiverPassword).Result;

                LogInfo($"Send to [{serverAddress}] channel [{receiverChannel}]: [{value ?? "NULL"}]");

                if (result == 0)
                {
                    LogInfo($"[{serverAddress}] channel [{receiverChannel}] receiver: Received.");
                }
                else if (result == 1)
                {
                    LogError($"[{serverAddress}] channel [{receiverChannel}] receiver: Password is wrong.");
                }
                else if (result == 2)
                {
                    LogError($"[{serverAddress}]: No receivers with channel [{receiverChannel}].");
                }
            }
            catch (Exception e)
            {
                OnConnectionFailed?.Invoke(e.Message);
            }
        }
Example #5
0
 public async void Clear()
 {
     try
     {
         await httpClient.DeleteAsync("http://localhost:5000/main");
     }
     catch
     {
         OnConnectionFailed?.Invoke();
     }
 }
Example #6
0
        internal void FailedToConnect(Connection connection, RejectReason reason)
        {
            if (_logger.Enabled(LogType.Warning))
            {
                _logger.Log(LogType.Warning, $"Connection Failed to connect: {reason}");
            }

            RemoveConnection(connection);

            // tell high level
            OnConnectionFailed?.Invoke(connection, reason);
        }
Example #7
0
        internal void FailedToConnect(Connection connection, RejectReason reason)
        {
            if (logger.IsLogTypeAllowed(LogType.Log))
            {
                logger.Log($"Connection Failed to connect: {reason}");
            }

            RemoveConnection(connection);

            // tell high level
            OnConnectionFailed?.Invoke(connection, reason);
        }
Example #8
0
        private void HandleConnectionFailed(Connection connection, Packet packet)
        {
            Debug.Assert(connection.State == ConnectionState.Connecting);

            var reason = (ConnectionFailedReason)packet.Data[2];

            Log.Info($"[ConnectionFailed]: {connection}, Reason={reason}");

            RemoveConnection(connection);

            // Callback to the user code
            OnConnectionFailed?.Invoke(connection, reason);
        }
Example #9
0
        internal void ConnectToServer()
        {
            try
            {
                tcpClient = new TcpClient(
                    Constants.SERVER_IP,
                    Constants.SERVER_PORT);

                networkStream = tcpClient.GetStream();
            }
            catch (Exception)
            {
                OnConnectionFailed.Invoke();
            }
        }
Example #10
0
        void HandleConnectionRefused(Connection connection, Packet packet)
        {
            switch (connection.State)
            {
            case ConnectionState.Connecting:
                var reason = (ConnectionFailedReason)packet.Data[2];
                Log.Trace($"Connection Refused: {reason}");
                RemoveConnection(connection);
                OnConnectionFailed?.Invoke(connection, reason);
                break;

            default:
                Assert.AlwaysFail();
                break;
            }
        }
Example #11
0
        public void Connect(string host, int port)
        {
            Disconnect();

            bool connected;

            try
            {
                if (mTcpClient == null)
                {
                    mTcpClient = new TcpClient(AddressFamily.InterNetwork);
                    mTcpClient.ReceiveBufferSize = RECEIVE_BUFFER_SIZE;
                    mTcpClient.NoDelay           = true;            // send data immediately upon calling NetworkStream.Write
                }

                IPAddress[] host_address = Dns.GetHostAddresses(host);
                //Start the async connect operation
                IAsyncResult connection_result = mTcpClient.BeginConnect(host_address, port, new AsyncCallback(ConnectCallback), mTcpClient);

                connected = connection_result.AsyncWaitHandle.WaitOne(CONNECTION_TIMEOUT);
            }
            catch (Exception e)
            {
                Debug.Log("[SnipeTCPClient] TCP Client initialization failed: " + e.Message);

                connected = false;
            }

            if (!connected)
            {
#if DEBUG
                Debug.Log("[SnipeTCPClient] TCP Client connection failed");
#endif

                if (mTcpClient == null)
                {
                    mTcpClient.Client?.Close();
                    mTcpClient?.Close();
                    mTcpClient = null;
                }

                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke();
                }
            }
        }
Example #12
0
 /// <summary>
 /// Connects to a server using an address
 /// </summary>
 public void Connect(string address)
 {
     if (CurrentMode == Mode.Idle)
     {
         tmpAddress = address;
         network.Connect(address);
     }
     else if (CurrentMode == Mode.Client)
     {
         var e = new Exception("Already connected to addr " + Address);
         OnConnectionFailed?.Invoke(e);
     }
     else
     {
         var e = new Exception("Already connected to addr " + Address);
         OnConnectionFailed?.Invoke(e);
     }
 }
Example #13
0
        void OnConnected(IAsyncResult result)
        {
            TcpClient client = result.AsyncState as TcpClient;

            try
            {
                client.EndConnect(result);
                networkStream = client.GetStream();
                OnConnented?.Invoke();
                Debug.Log("成功连接到服务器!!!");
                networkStream.BeginRead(byteBuffer, 0, MAX_READ, OnRead, client);
            }
            catch (Exception ex)
            {
                OnConnectionFailed?.Invoke();
                Debug.LogErrorFormat("连接失败:{0}", ex.ToString());
                Close();
            }
        }
Example #14
0
        private void ConnectCallback(IAsyncResult result)
        {
            try
            {
                //We are connected successfully
                NetworkStream network_stream = mTcpClient.GetStream();

                byte[] buffer = new byte[mTcpClient.ReceiveBufferSize];

                //Now we are connected start asyn read operation
                network_stream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);

                if (mBufferSream == null)
                {
                    mBufferSream          = new MemoryStream();
                    mBufferSream.Capacity = MESSAGE_BUFFER_SIZE;
                }
                else
                {
                    mBufferSream.SetLength(0);                      // "clearing" buffer
                }

                mConnected = true;

                if (OnConnectionSucceeded != null)
                {
                    OnConnectionSucceeded.Invoke();
                }
            }
            catch (Exception)
            {
                //Debug.Log("[SnipeTCPClient] ConnectCallback: " + e.Message);

                mConnected = false;

                // send event
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke();
                }
            }
        }
Example #15
0
        void ProcessNetworkEvent(NetworkEvent e)
        {
            switch (e.Type)
            {
            case NetEventType.ServerInitialized:
                OnServerStartSuccess?.Invoke(e);
                break;

            case NetEventType.ServerInitFailed:
                OnServerStartFailure?.Invoke(e);
                break;

            // Received after network.StopServer
            case NetEventType.ServerClosed:
                OnServerStopped?.Invoke(e);
                break;


            case NetEventType.NewConnection:
                OnNewConnection?.Invoke(e);
                break;

            case NetEventType.ConnectionFailed:
                OnConnectionFailed?.Invoke(e);
                break;

            case NetEventType.Disconnected:
                OnDisconnection?.Invoke(e);
                break;


            case NetEventType.ReliableMessageReceived:
                OnMessageReceived?.Invoke(e, true);
                break;

            case NetEventType.UnreliableMessageReceived:
                OnMessageReceived?.Invoke(e, false);
                break;
            }
        }
Example #16
0
        public async void GetStatistic(SendDataView input)
        {
            try
            {
                var data = new SendData();
                data.Data     = input.Data.GetDeterministicHashCode().ToString();
                data.TypeName = input.TypeName;
                var j = JsonConvert.SerializeObject(data);
                var c = new StringContent(j);
                c.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var result = await httpClient.PutAsync("http://localhost:5000/main/", c);

                data.TypeName = await result.Content.ReadAsStringAsync();

                statQueue.Enqueue(data);
                OnGetStatistic?.Invoke();
            }
            catch
            {
                OnConnectionFailed?.Invoke();
            }
        }
Example #17
0
        /// <summary>
        /// Invoked when the network peer has received a message
        /// </summary>
        /// <param name="state">The object that invoked this (NetPeer)</param>
        private void MessageReceived(object state)
        {
            // Get the incoming message
            NetIncomingMessage inMsg = ((NetPeer)state).ReadMessage();

            // We don't want the server to crash on one bad packet
            try
            {
                // Determine the message type to correctly handle it
                switch (inMsg.MessageType)
                {
                // Handle when a client's status has changed
                case NetIncomingMessageType.StatusChanged:
                    // Gets the status and reason
                    NetConnectionStatus status = (NetConnectionStatus)inMsg.ReadByte();
                    string reason = inMsg.ReadString();

                    // Depending on the status, we handle players joining or leaving
                    switch (status)
                    {
                    case NetConnectionStatus.Disconnected:

                        // If the reason the is shutdown message, we're good
                        if (reason.Equals(NetSettings.DEFAULT_SERVER_SHUTDOWN_MESSAGE))
                        {
                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        // Otherwise if the reason is that \/ , then we timed out
                        else if (reason.Equals("Failed to establish connection - no response from remote host", StringComparison.InvariantCultureIgnoreCase))
                        {
                            OnConnectionTimedOut?.Invoke(this, EventArgs.Empty);

                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        else if (reason.StartsWith("You have been kicked:"))
                        {
                            OnKicked?.Invoke(this, reason);

                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }
                        // Otherwise the connection failed for some other reason
                        else
                        {
                            OnDisconnected?.Invoke(this, EventArgs.Empty);
                        }

                        if (isApproving)
                        {
                            OnConnectionFailed?.Invoke(this, reason);
                        }

                        isApproving = false;

                        // Clear local state and forget connected server tag
                        myLocalState.Clear();
                        myConnectedServer = null;
                        isReady           = false;
                        isHost            = false;
                        myKnownPlayers.Clear();
                        myLocalState.Clear();
                        myHand.Clear();

                        break;

                    case NetConnectionStatus.RespondedAwaitingApproval:
                        isApproving = true;
                        break;

                    // We connected
                    case NetConnectionStatus.Connected:
                        isApproving = false;
                        // invoked the onConnected event
                        OnConnected?.Invoke(this, EventArgs.Empty);
                        break;
                    }

                    break;

                // Handle when the server has received a discovery request
                case NetIncomingMessageType.DiscoveryResponse:
                    // Read the server tag from the packet
                    ServerTag serverTag = ServerTag.ReadFromPacket(inMsg);

                    // Notify that we discovered a server
                    OnServerDiscovered?.Invoke(this, serverTag);

                    break;

                // Handles when the server has received data
                case NetIncomingMessageType.Data:
                    HandleMessage(inMsg);
                    break;
                }
            }
            // An exception has occured parsing the packet
            catch (Exception e)
            {
                //Log the exception
                Logger.Write(e);
            }
        }
Example #18
0
        /// <summary>
        /// Dequeues all the messages from Discord and invokes appropriate methods. This will process the message and update the internal state before invoking the events. Returns the messages that were invoked and in the order they were invoked.
        /// </summary>
        /// <returns>Returns the messages that were invoked and in the order they were invoked.</returns>
        public IMessage[] Invoke()
        {
            //Dequeue all the messages and process them
            IMessage[] messages = connection.DequeueMessages();
            for (int i = 0; i < messages.Length; i++)
            {
                //Do a bit of pre-processing
                IMessage message = messages[i];
                HandleMessage(message);

                //Invoke the appropriate methods
                switch (message.Type)
                {
                case MessageType.Ready:
                    if (OnReady != null)
                    {
                        OnReady.Invoke(this, message as ReadyMessage);
                    }
                    break;

                case MessageType.Close:
                    if (OnClose != null)
                    {
                        OnClose.Invoke(this, message as CloseMessage);
                    }
                    break;

                case MessageType.Error:
                    if (OnError != null)
                    {
                        OnError.Invoke(this, message as ErrorMessage);
                    }
                    break;

                case MessageType.PresenceUpdate:
                    if (OnPresenceUpdate != null)
                    {
                        OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                    }
                    break;

                case MessageType.ConnectionEstablished:
                    if (OnConnectionEstablished != null)
                    {
                        OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                    }
                    break;

                case MessageType.ConnectionFailed:
                    if (OnConnectionFailed != null)
                    {
                        OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                    }
                    break;

                default:
                    //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                    Console.WriteLine($"Message was queued with no appropriate handle! {message.Type}");
                    break;
                }
            }

            //Finally, return the messages
            return(messages);
        }
Example #19
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    PresenceMessage pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                ReadyMessage rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    JoinRequestMessage jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    SubscribeMessage sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    UnsubscribeMessage unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
 public void ConnectionFailed(ConnectionFailedInfo failInfo)
 {
     OnConnectionFailed?.Invoke(this, failInfo);
 }
Example #21
0
        /// <summary>
        /// Sends a byte array to several recipient peers
        /// </summary>
        /// <param name="recipients">A list of the recipient peer IDs</param>
        /// <param name="bytes">The byte array to send</param>
        /// <param name="reliable">Whether data is sent UDP/TCP style</param>
        public void SendRaw
            (List <short> recipients, byte[] bytes, bool reliable = false)
        {
            if (recipients == null || recipients.Count == 0)
            {
                recipients = new List <short> {
                    1
                }
            }
            ;

            var message = new Message {
                sender     = ID,
                recipients = recipients.ToArray(),
                bytes      = bytes
            };
            var bytesToSend = message.Serialize();

            // If we're a client, we only send to the server.
            // The server will pass on the message to clients in recipient list
            if (CurrentMode == Mode.Client)
            {
                network.SendData(
                    id: serverCID,
                    data: bytesToSend,
                    offset: 0,
                    len: bytesToSend.Length,
                    reliable: reliable
                    );
            }
            // If we're the server, we send to all the recipients
            else if (CurrentMode == Mode.Server)
            {
                foreach (var recipient in recipients)
                {
                    if (recipient != ID)
                    {
                        network.SendData(
                            id: new ConnectionId(recipient),
                            data: bytesToSend,
                            offset: 0,
                            len: bytesToSend.Length,
                            reliable: reliable
                            );
                    }
                }
            }
        }

        // ================================================
        // NETWORK HANDLERS
        // ================================================
        void Network_OnServerStartSuccess(NetworkEvent e)
        {
            ID          = 0; // server ID is 0
            CurrentMode = Mode.Server;
            Address     = tmpAddress;
            OnServerStartSuccess?.Invoke();
            OnReceiveID?.Invoke(ID);
        }

        void Network_OnServerStartFailure(NetworkEvent e)
        {
            Reset();
            OnServerStartFailure?.Invoke(
                new Exception(e.GetDataAsString() + e.Info)
                );
        }

        // This is called only on the server, not on the client side
        void Network_OnServerStopped(NetworkEvent e)
        {
            // Using a reserved packet tag,
            // we let all the clients know that we have closed the server
            if (CurrentMode == Mode.Server)
            {
                SendPacket(
                    Peers,
                    new Packet().WithTag(Packet.ReservedTags.ServerClosed),
                    true
                    );
                Reset();
                OnServerStop?.Invoke();
            }
        }

        void Network_OnNewConnection(NetworkEvent e)
        {
            if (CurrentMode == Mode.Server)
            {
                var theNewID = e.ConnectionId.id;

                // Notify a new client of its ID is using a reserved tag packet
                var tag    = Packet.ReservedTags.ClientSetID;
                var packet = new Packet().With(tag, theNewID.GetBytes());
                SendPacket(theNewID, packet, true);

                // Using reserved tag packets, let the new client know about
                // all the old clients and the old clients about the new client
                foreach (var anOldID in Peers)
                {
                    tag    = Packet.ReservedTags.ClientJoined;
                    packet = new Packet().With(tag, anOldID.GetBytes());
                    SendPacket(theNewID, packet, true);

                    tag    = Packet.ReservedTags.ClientJoined;
                    packet = new Packet().With(tag, theNewID.GetBytes());
                    SendPacket(anOldID, packet, true);
                }

                Peers.Add(theNewID);
                OnClientJoined?.Invoke(theNewID);
            }
            else if (CurrentMode == Mode.Idle)
            {
                serverCID   = e.ConnectionId;
                CurrentMode = Mode.Client;
                // Add the server as a peer. To the client, server ID is 0
                Peers.Add(0);
                Address = tmpAddress;
                OnConnected?.Invoke();
            }
        }

        void Network_OnConnectionFailed(NetworkEvent e)
        {
            Reset();
            var ex = new Exception(e.GetDataAsString() + e.Info);

            OnConnectionFailed?.Invoke(ex);
        }

        void Network_OnDisconnection(NetworkEvent e)
        {
            if (CurrentMode == Mode.Server)
            {
                Peers.Remove(e.ConnectionId.id);

                // Using a reserved tag, we let all the other clients know
                // that a client has left
                var tag    = Packet.ReservedTags.ClientLeft;
                var packet = new Packet().WithTag(tag)
                             .WithPayload(e.ConnectionId.id.GetBytes());
                SendPacket(Peers, packet, true);

                OnClientLeft?.Invoke(e.ConnectionId.id);
            }
            else if (CurrentMode == Mode.Client)
            {
                Reset();
                OnDisconnected?.Invoke();
            }
        }

        void Network_OnMessageReceived(NetworkEvent e, bool reliable)
        {
            var data = e.GetDataAsByteArray();

            var message = Message.Deserialize(data);
            var packet  = Packet.Deserialize(message.bytes);

            // Try to look for reserved keywords
            if (packet != null && packet.Tag.StartsWith("reserved"))
            {
                switch (packet.Tag)
                {
                case Packet.ReservedTags.ClientJoined:
                    if (CurrentMode == Mode.Client)
                    {
                        var cid = packet.Payload.ToShort();
                        Peers.Add(cid);
                        OnClientJoined?.Invoke(cid);
                    }
                    break;

                case Packet.ReservedTags.ClientLeft:
                    if (CurrentMode == Mode.Client)
                    {
                        var cid = packet.Payload.ToShort();
                        Peers.Remove(cid);
                        OnClientLeft?.Invoke(cid);
                    }
                    break;

                case Packet.ReservedTags.ClientSetID:
                    if (CurrentMode == Mode.Client)
                    {
                        ID = packet.Payload.ToShort();
                        OnReceiveID?.Invoke(ID);
                    }
                    break;

                case Packet.ReservedTags.ServerClosed:
                    Reset();
                    OnRemoteServerClosed?.Invoke();
                    break;
                }
                return;
            }

            // If we were an intended recipient
            if (message.recipients.Contains(ID))
            {
                if (packet != null)
                {
                    OnPacketReceived?.Invoke(message.sender, packet);
                }
                else
                {
                    OnBytesReceived?.Invoke(message.sender, message.bytes);
                }
            }

            // If we're a server, forward the message to the intended
            // recipients, except ourselves
            if (CurrentMode == Mode.Server)
            {
                foreach (var recipient in message.recipients)
                {
                    if (recipient != 0)
                    {
                        if (packet == null)
                        {
                            packet = new Packet();
                            packet.WithPayload(message.bytes);
                        }
                        var m = new Message {
                            sender     = message.sender,
                            recipients = new short[] { recipient },
                            bytes      = packet.Serialize()
                        };
                        network.SendData(
                            id: new ConnectionId(recipient),
                            data: m.Serialize(),
                            offset: 0,
                            len: m.Serialize().Length,
                            reliable: reliable
                            );
                    }
                }
            }
        }

        void Reset()
        {
            ID          = -1;
            CurrentMode = Mode.Idle;
            foreach (var peer in Peers)
            {
                OnClientLeft?.Invoke(peer);
            }
            Peers.Clear();
            Address = null;
        }
 private void Subsribe()
 {
     _manager.RdpViewer.OnApplicationClose          += delegate(object application) { OnApplicationClose?.Invoke(application); };
     _manager.RdpViewer.OnApplicationOpen           += delegate(object application) { OnApplicationOpen?.Invoke(application); };
     _manager.RdpViewer.OnApplicationUpdate         += delegate(object application) { OnApplicationUpdate?.Invoke(application); };
     _manager.RdpViewer.OnAttendeeConnected         += delegate(object attendee) { OnAttendeeConnected?.Invoke(attendee); };
     _manager.RdpViewer.OnAttendeeDisconnected      += delegate(object info) { OnAttendeeDisconnected?.Invoke(info); };
     _manager.RdpViewer.OnAttendeeUpdate            += delegate(object attendee) { OnAttendeeUpdate?.Invoke(attendee); };
     _manager.RdpViewer.OnChannelDataReceived       += delegate(object channel, int id, string data) { OnChannelDataReceived?.Invoke(channel, id, data); };
     _manager.RdpViewer.OnChannelDataSent           += delegate(object channel, int id, int sent) { OnChannelDataSent?.Invoke(channel, id, sent); };
     _manager.RdpViewer.OnConnectionAuthenticated   += delegate(object sender, EventArgs args) { OnConnectionAuthenticated?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionEstablished     += delegate(object sender, EventArgs args) { OnConnectionEstablished?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionFailed          += delegate(object sender, EventArgs args) { OnConnectionFailed?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionTerminated      += delegate(int reason, int info) { OnConnectionTerminated?.Invoke(reason, info); };
     _manager.RdpViewer.OnControlLevelChangeRequest += delegate(object attendee, CTRL_LEVEL level) { OnControlLevelChangeRequest?.Invoke(attendee, level); };
     _manager.RdpViewer.OnError                        += delegate(object info) { OnError?.Invoke(info); };
     _manager.RdpViewer.OnFocusReleased                += delegate(int direction) { OnFocusReleased?.Invoke(direction); };
     _manager.RdpViewer.OnGraphicsStreamPaused         += delegate(object sender, EventArgs args) { OnGraphicsStreamPaused?.Invoke(sender, args); };
     _manager.RdpViewer.OnGraphicsStreamResumed        += delegate(object sender, EventArgs args) { OnGraphicsStreamResumed?.Invoke(sender, args); };
     _manager.RdpViewer.OnSharedDesktopSettingsChanged += delegate(int width, int height, int colordepth) { OnSharedDesktopSettingsChanged?.Invoke(width, height, colordepth); };
     _manager.RdpViewer.OnSharedRectChanged            += delegate(int left, int top, int right, int bottom) { OnSharedRectChanged?.Invoke(left, top, right, bottom); };
     _manager.RdpViewer.OnWindowClose                  += delegate(object window) { OnWindowClose?.Invoke(window); };
     _manager.RdpViewer.OnWindowOpen                   += delegate(object window) { OnWindowOpen?.Invoke(window); };
     _manager.RdpViewer.OnWindowUpdate                 += delegate(object window) { OnWindowUpdate?.Invoke(window); };
 }
        public Multiplayer(string Server, string Channel, string Username)
        {
            this.Channel  = Channel;
            this.Username = Username;

            socket = new WebSocket(Server);

            socket.OnOpen += (sender, e) =>
            {
                MessageConnect connect = new MessageConnect()
                {
                    Channel  = this.Channel,
                    Username = this.Username,
                    Version  = Shared.Version
                };

                socket.Send(JsonConvert.SerializeObject(connect));
            };

            socket.OnClose += (sender, e) =>
            {
                if (!ManualClose && !string.IsNullOrWhiteSpace(e.Reason))
                {
                    OnConnectionFailed?.Invoke(this, new ConnectionFailedEventArgs());
                }
            };

            socket.OnMessage += (sender, e) =>
            {
                MessageType messageType = JsonConvert.DeserializeObject <MessageType>(e.Data);
                if (messageType.Type == 0) // Connection Successful
                {
                    MessageConnectionSuccessful connectionSuccessful = JsonConvert.DeserializeObject <MessageConnectionSuccessful>(e.Data);

                    IsHost = connectionSuccessful.IsHost;

                    ConnectionSuccessfulEventArgs succ = new ConnectionSuccessfulEventArgs()
                    {
                        IsHost       = connectionSuccessful.IsHost,
                        HostUsername = connectionSuccessful.HostUsername
                    };

                    OnConnectionSuccessful?.Invoke(this, succ);
                }
                else if (messageType.Type == 1) // Username in use
                {
                    OnUsernameInUse?.Invoke(this, new UsernameInUseEventArgs());
                    socket.Close();
                }
                else if (messageType.Type == 2) // Host left the channel
                {
                    OnHostLeftChannel?.Invoke(this, new HostLeftChannelEventArgs());
                    socket.Close();
                }
                else if (messageType.Type == 3)
                {
                    MessageVersionMismatch mismatch = JsonConvert.DeserializeObject <MessageVersionMismatch>(e.Data);

                    var args = new VersionMismatchEventArgs()
                    {
                        Version = mismatch.Version
                    };

                    OnVersionMismatch?.Invoke(this, args);
                }
                // -------
                else if (messageType.Type == 10) // User Joined
                {
                    MessageUserJoined user = JsonConvert.DeserializeObject <MessageUserJoined>(e.Data);

                    var args = new UserJoinedEventArgs()
                    {
                        Username = user.Username
                    };

                    OnUserJoined?.Invoke(this, args);
                }
                else if (messageType.Type == 11) // User Left
                {
                    MessageUserLeft user = JsonConvert.DeserializeObject <MessageUserLeft>(e.Data);

                    var args = new UserLeftEventArgs()
                    {
                        Username = user.Username
                    };

                    OnUserLeft?.Invoke(this, args);
                }
                else if (messageType.Type == 12) // Chat Message
                {
                    MessageChatMessage chatMessage = JsonConvert.DeserializeObject <MessageChatMessage>(e.Data);

                    var args = new ChatMessageEventArgs()
                    {
                        Username = chatMessage.Username,
                        Message  = chatMessage.Message
                    };

                    OnChatMessage?.Invoke(this, args);
                }
                // -------
                else if (messageType.Type == 20) // Time Update
                {
                    MessageTimeUpdate timeUpdate = JsonConvert.DeserializeObject <MessageTimeUpdate>(e.Data);

                    var args = new TimeUpdateEventArgs()
                    {
                        Remaining = timeUpdate.Remaining,
                        Total     = timeUpdate.Total
                    };

                    OnTimeUpdate?.Invoke(this, args);
                }
                else if (messageType.Type == 21) // Send Effect
                {
                    MessageEffect effect = JsonConvert.DeserializeObject <MessageEffect>(e.Data);

                    var args = new EffectEventArgs()
                    {
                        Word     = effect.Word,
                        Duration = effect.Duration,
                        Voter    = effect.Voter,
                        Seed     = effect.Seed
                    };

                    OnEffect?.Invoke(this, args);
                }
                else if (messageType.Type == 22) // Votes
                {
                    MessageVotes votes = JsonConvert.DeserializeObject <MessageVotes>(e.Data);

                    var args = new VotesEventArgs()
                    {
                        Effects    = votes.Effects,
                        Votes      = votes.Votes,
                        LastChoice = votes.LastChoice
                    };

                    OnVotes?.Invoke(this, args);
                }
            };
        }