コード例 #1
0
ファイル: IrcClient.cs プロジェクト: nfp-projects/irc_bot
        private void ConnectComplete(IAsyncResult result)
        {
            Socket.EndConnect(result);

            NetworkStream = new NetworkStream(Socket);
            if (UseSSL)
            {
                NetworkStream = new SslStream(NetworkStream, false, new RemoteCertificateValidationCallback(CheckCertificate));
                try
                {
                    ((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname);
                }
                catch (Exception)
                {
                    NetworkStream.Dispose();
                    Socket.Dispose();
                    if (OnDisconnected != null)
                    {
                        OnDisconnected(this, new EventArgs());
                    }
                    return;
                }
            }

            Read();

            if (!string.IsNullOrEmpty(User.Password))
            {
                SendRawMessage("PASS {0}", User.Password);
            }
            SendRawMessage("NICK {0}", User.Nick);
            // hostname, servername are ignored by most IRC servers
            SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
            PingTimer.Start();
        }
コード例 #2
0
ファイル: IrcClient.cs プロジェクト: nfp-projects/irc_bot
        public async void Quit(string reason)
        {
            if (IsQuitting)
            {
                return;
            }
            IsQuitting = true;

            if (reason == null)
            {
                await SendRawMessage("QUIT");
            }
            else
            {
                await SendRawMessage("QUIT :{0}", reason);
            }

            Socket.BeginDisconnect(false, ar =>
            {
                Socket.EndDisconnect(ar);
                NetworkStream.Close();
                NetworkStream.Dispose();
                NetworkStream = null;
                Socket.Dispose();
                if (OnDisconnected != null)
                {
                    OnDisconnected(this, new EventArgs());
                }
            }, null);
            PingTimer.Dispose();
        }
コード例 #3
0
ファイル: IrcClient.cs プロジェクト: ikriz/ChatSharp
        private void ConnectComplete(IAsyncResult result)
        {
            Socket.EndConnect(result);

            NetworkStream = new NetworkStream(Socket);
            if (UseSSL)
            {
                if (IgnoreInvalidSSL)
                {
                    NetworkStream = new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true);
                }
                else
                {
                    NetworkStream = new SslStream(NetworkStream);
                }
                ((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname);
            }

            NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null);
            // Write login info
            if (!string.IsNullOrEmpty(User.Password))
            {
                SendRawMessage("PASS {0}", User.Password);
            }
            SendRawMessage("NICK {0}", User.Nick);
            // hostname, servername are ignored by most IRC servers
            SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
            PingTimer.Start();
        }
コード例 #4
0
        private void SendPing()
        {
            if (m_Client != null && m_Client.Connected && m_User.IsAuthenticated && ClientPingMode == PingMode.Initiative)
            {
                if (_lastSendTime.AddSeconds(PingInterval) > DateTime.Now)
                {
                    //未到时间
                    return;
                }

                try
                {
                    byte[] sendData = PingData.ToByte();
                    m_Client.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, null, m_Client);

                    UpdateTimeForInitiativePing();
                    LogOpInfo("Send--Ping", pingData);
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                PingTimer.Stop();
            }
        }
コード例 #5
0
        public async void Start()
        {
            if (!CanStart())
            {
                return;
            }

            WrapperProcess = new Process();

            var processStartInfo = new ProcessStartInfo(ExecutablePath);

            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardInput  = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.CreateNoWindow         = true;
            WrapperProcess.StartInfo = processStartInfo;
            WrapperProcess.Start();

            await Task.Factory.StartNew(() => ReadNextLine(false));

            await Task.Factory.StartNew(() => ReadNextLine(true));

            PingTimer.Start();
            ConnectionTimer.Start();
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: hamwich3/WinPLCChangeIP
        private void ChangeIP_Click(object sender, EventArgs e)
        {
            PingTimer.Stop();
            Ping      ping  = new Ping();
            PingReply reply = ping.Send(plcIPAddressBox.IPAddress, 1500);

            Console.WriteLine(reply.Status.ToString() + " " + plcIPAddressBox.IPAddress.ToString());
            if (reply.Status == IPStatus.Success)
            {
                DialogResult result = MessageBox.Show("Detected another device with this IP address. Use this address anyway?",
                                                      "IP Address in Use!", MessageBoxButtons.OKCancel);
                if (result == DialogResult.Cancel)
                {
                    return;
                }
            }
            if (PLCGrid.SelectedRows.Count <= 0)
            {
                MessageBox.Show("Select PLC from List.", "Error!");
                return;
            }
            DetectedPLC plc = (DetectedPLC)DiscoverPLC.PLCbs.Current;

            if (plc == null)
            {
                MessageBox.Show("Null PLC Exception!", "Error!");
                return;
            }
            DiscoverPLC.changeIP(plc, plcIPAddressBox.IPAddress);
            FindPLCs();
        }
コード例 #7
0
ファイル: Pinger.cs プロジェクト: Unity-Technologies/MGOBE
        ///////////////////////////////// PONG //////////////////////////////////
        public void Ping(Action <ResponseEvent> callback)
        {
            PingTimer.Stop();
            if (string.IsNullOrEmpty(RequestHeader.AuthKey))
            {
                return;
            }
            var startTime = DateTime.Now;
            var routeId   = FrameSender?.RoomInfo?.RouteId ?? "";
            var conType   = this.Id == 1 ? ConnectionType.Relay : ConnectionType.Common;
            var body      = new HeartBeatReq {
                ConType = conType,
                RouteId = routeId
            };

            void PongResposne(bool send, DecodeRspResult result, Action <ResponseEvent> cb)
            {
                this.HandlePong(send, result, startTime);
            }

            var seq = this.Send(body.ToByteString(), (int)ProtoCmd.ECmdHeartBeatReq, PongResposne, callback);

            // if(this.Id == 1) Debugger.Log("send heartBeat: {0}", seq);
            CurrentSeq = seq;
            this.PongTimer.SetTimer(() => HandlePongTimeout(seq), this.Timeout);
        }
コード例 #8
0
        public void EndProtocolPeriod()
        {
            try
            {
                Debug.WriteLine("Ending Protocol Period");
                Logger.LogInformation("Ending Protocol Period");

                lock (_receivedAckLock)
                {
                    if (ActiveNode != null)
                    {
                        if (!ReceivedAck)
                        {
                            Debug.WriteLine($"No response from Node {ActiveNode.Endpoint}, marking as dead.");
                            Logger.LogInformation($"No response from Node {ActiveNode.Endpoint}, marking as dead.");

                            AddBroadcastMessage(new DeadMessage(ActiveNode));
                        }
                        else
                        {
                            Debug.WriteLine($"Response from Node {ActiveNode.Endpoint}, marking as alive.");
                            Logger.LogInformation($"Response from Node {ActiveNode.Endpoint}, marking as alive.");

                            //  Add the node back into the queue.
                            AddNode(ActiveNode);
                        }

                        ActiveNode = null;

                        ProtocolPeriodsComplete++;

                        if (InitialNodeCount == ProtocolPeriodsComplete)
                        {
                            Debug.WriteLine("Shuffing Nodes");
                            Logger.LogInformation("Shuffing Nodes");

                            ShuffleNodes();

                            lock (_nodesLock)
                            {
                                InitialNodeCount = Nodes.Count;
                            }

                            ProtocolPeriodsComplete = 0;
                        }
                    }

                    ReceivedAck = false;
                    ProtocolTimer.Stop();
                    ProtocolTimerRunning = false;
                    PingTimer.Stop();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"{e.ToString()}: {e.StackTrace}");
                Logger.LogError(e, string.Empty);
            }
        }
コード例 #9
0
ファイル: Form1.cs プロジェクト: hamwich3/WinPLCChangeIP
        private void catchbtn_Click(object sender, EventArgs e)
        {
            PingTimer.Stop();
            Catch catch1 = new Catch(plcIPAddressBox.IPAddress, DiscoverPLC);

            catch1.ShowDialog();
            //DiscoverPLC.DiscoverPLCs();
            PingTimer.Start();
        }
コード例 #10
0
        public override void Exit()
        {
            HandleLines = false;

            PingTimer.Stop();
            ConnectionTimer.Stop();

            base.Exit();
        }
コード例 #11
0
ファイル: ClientController.cs プロジェクト: vaginessa/Code
        public override void Shutdown()
        {
            base.Shutdown();

            if (PingTimer != null)
            {
                PingTimer.Dispose();
                PingTimer = null;
            }
        }
コード例 #12
0
ファイル: IrcClient.cs プロジェクト: kria/ChatSharp
 public void Quit(string reason)
 {
     if (reason == null)
     {
         SendRawMessage("QUIT");
     }
     else
     {
         SendRawMessage("QUIT :{0}", reason);
     }
     Socket.Disconnect(false);
     PingTimer.Dispose();
 }
コード例 #13
0
ファイル: IrcClient.cs プロジェクト: kria/ChatSharp
 private void ConnectComplete(IAsyncResult result)
 {
     Socket.EndConnect(result);
     Socket.BeginReceive(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, SocketFlags.None, DataRecieved, null);
     // Write login info
     if (!string.IsNullOrEmpty(User.Password))
     {
         SendRawMessage("PASS {0}", User.Password);
     }
     SendRawMessage("NICK {0}", User.Nick);
     // hostname, servername are ignored by most IRC servers
     SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
     PingTimer.Start();
 }
コード例 #14
0
        public object Put(PingTimer request)
        {
            string timerContractAdr = AppServices.GetEcosystemAdr(request.ContractAdr).TimerContractAdr;

            // Activate or deactivate the auto ping scheduling functionality
            AppServices.configureTimerPing(timerContractAdr, request.SigningPrivateKey, request.AutoSchedulePingDuration);
            // Submit and return the transaction hash of the broadcasted ping transaction
            return(AppServices.createSignPublishTransaction(
                       AppModelConfig.TIMER.abi,
                       timerContractAdr,
                       request.SigningPrivateKey,
                       "ping"
                       ));
        }
コード例 #15
0
        private void PingNode(SwimNode node)
        {
            //  Ping node directly

            PingCorrelationId = Ulid.NewUlid();

            Debug.WriteLine($"Pinging node {node.Endpoint}.");
            Logger.LogInformation($"Pinging node {node.Endpoint}.");

            ProtocolProvider.SendMessage(node, new PingMessage(PingCorrelationId.Value)
            {
                SourceNode = ProtocolProvider.Node
            });

            PingTimer.Start();
        }
コード例 #16
0
ファイル: IrcClient.cs プロジェクト: FransRousseau/ChatSharp
        private void ConnectComplete(IAsyncResult result)
        {
            if (this.Connected)
            {
                SocketError socketError = SocketError.Success;
                try
                {
                    Socket.EndConnect(result);

                    NetworkStream = new NetworkStream(Socket);
                    if (UseSSL)
                    {
                        if (IgnoreInvalidSSL)
                        {
                            NetworkStream = new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true);
                        }
                        else
                        {
                            NetworkStream = new SslStream(NetworkStream);
                        }
                        (( SslStream )NetworkStream).AuthenticateAsClient(ServerHostname);
                    }

                    NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null);
                }
                catch (Exception ex)
                {
                    if (this.SocketConnectionError == null)
                    {
                        throw ex;
                    }
                    this.OnSocketConnectionError(new SocketUnhandledExceptionEventArgs(ex));
                    return;
                }
                // Write login info
                if (!string.IsNullOrEmpty(User.Password))
                {
                    SendRawMessage("PASS {0}", User.Password);
                }
                SendRawMessage("NICK {0}", User.Nick);
                // hostname, servername are ignored by most IRC servers
                SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
                PingTimer.Start();
            }
            this.ConnectCompleted = true;
        }
コード例 #17
0
 public void Quit(string reason)
 {
     if (reason == null)
     {
         SendRawMessage("QUIT");
     }
     else
     {
         SendRawMessage("QUIT :{0}", reason);
     }
     Socket.BeginDisconnect(false, ar =>
     {
         Socket.EndDisconnect(ar);
         NetworkStream.Dispose();
         NetworkStream = null;
     }, null);
     PingTimer.Dispose();
 }
コード例 #18
0
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Disconnect()
        {
            if (m_Client.Connected)
            {
                //close
                SendDisconnect();
                m_User.IsAuthenticated = false;
                m_Client.Disconnect(true);
                m_Client.Close(1000);
                PingTimer.Stop();
            }
            if (OnDisconnect != null)
            {
                OnDisconnect();
            }

            LogInfo("断开连接", null);
        }
コード例 #19
0
        private void ConnectComplete(IAsyncResult result)
        {
            try
            {
                Socket.EndConnect(result);
                NetworkStream = new NetworkStream(Socket);
                if (UseSSL)
                {
                    if (IgnoreInvalidSSL)
                    {
                        NetworkStream = new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true);
                    }
                    else
                    {
                        NetworkStream = new SslStream(NetworkStream);
                    }
                    ((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname);
                }

                NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null);
                // Begin capability negotiation
                //SendRawMessage("CAP LS 302");
                // Write login info
                if (!string.IsNullOrEmpty(User.Password))
                {
                    SendRawMessage("PASS {0}", User.Password);
                }
                //SendRawMessage("NICK {0}", User.Nick);
                SendRawMessage($"USER MO.{Program.ID} 0 * :3.3.4 MO CnCNet");
                // hostname, servername are ignored by most IRC servers
                SendRawMessage($"NICK {Program.Name}");
                //SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
                PingTimer.Start();
            }
            catch (SocketException e)
            {
                OnNetworkError(new SocketErrorEventArgs(e.SocketErrorCode));
            }
            catch (Exception e)
            {
                OnError(new Events.ErrorEventArgs(e));
            }
        }
コード例 #20
0
ファイル: Connection.cs プロジェクト: isaveu/uwp-multiplayer
        private async void SendPing(object state)
        {
            CheckPing(null);

            if (pingReplyReceived)
            {
                // Game.Log("Sending ping request to player (" + PlayerId + ").");

                pingReplyReceived = false;
                PingTimer.Restart();

                Tuple <short, byte[]> pingPacket = CreatePacket(Packets.PingRequest, null);
                await SendPacket(pingPacket);
            }
            else
            {
                Game.Log("Ping from player (" + PlayerId + ") not yet received.");
            }
        }
コード例 #21
0
ファイル: IrcClient.cs プロジェクト: TETYYS/ChatSharp
        /// <summary>
        /// Send a QUIT message with a reason and disconnect.
        /// </summary>
        public async ValueTask Quit(string reason)
        {
            if (reason == null)
            {
                await SendRawMessage("QUIT");
            }
            else
            {
                await SendRawMessage("QUIT :{0}", reason);
            }

            try { TcpClient.Close(); } catch { }
            TcpClient.Dispose();
            TcpClient = null;

            StreamReader = null;
            try { Pipe.Writer.Complete(); } catch { }
            try { Pipe.Reader.Complete(); } catch { }
            try { RW.Writer.Complete(); } catch { }
            Pipe = null;

            PingTimer.Dispose();
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: hamwich3/WinPLCChangeIP
        private void FindPLCs()
        {
            Thread t = new Thread(delegate()
            {
                this.BeginInvoke(new Action(delegate()
                {
                    PingTimer.Stop();
                    changeCursor(Cursors.WaitCursor);
                    EnableButtons(false);
                    DiscoverPLC.PLCbs.Clear();
                    DiscoverPLC.DiscoverPLCs();
                    changeCursor(Cursors.Default);
                    EnableButtons(true);
                    DiscoverPLC.PLCbs.ResetBindings(false);
                    PLCGrid.ClearSelection();
                    PingTimer.Start();
                }));
                lastSelectedRow = -1;
            });

            t.Start();
            this.ActiveControl = Discoverbtn;
            this.ActiveControl = null;
        }
コード例 #23
0
        /// <summary>
        /// Initiate a new Digital Society connection.
        /// </summary>
        /// <param name="mud_address">The IP address or hostname of the target server</param>
        /// <param name="port">The target port.</param>
        public static void Initiate(string mud_address, int port)
        {
            client = new NetObjectClient();
            client.OnDisconnected += (o, a) =>
            {
                if (!UserDisconnect)
                {
                    Desktop.PushNotification("digital_society_connection", "Disconnected from Digital Society.", "The ShiftOS kernel has been disconnected from the Digital Society. We are attempting to re-connect you.");
                    TerminalBackend.PrefixEnabled = true;
                    ConsoleEx.ForegroundColor     = ConsoleColor.Red;
                    ConsoleEx.Bold = true;
                    Console.Write($@"Disconnected from MUD: ");
                    ConsoleEx.Bold            = false;
                    ConsoleEx.Italic          = true;
                    ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("You have been disconnected from the multi-user domain for an unknown reason. Your save data is preserved within the kernel and you will be reconnected shortly.");
                    TerminalBackend.PrefixEnabled = true;
                    TerminalBackend.PrintPrompt();
                    Initiate(mud_address, port);
                }
            };
            client.OnReceived += (o, a) =>
            {
                if (PingTimer.IsRunning)
                {
                    DigitalSocietyPing = PingTimer.ElapsedMilliseconds;
                    PingTimer.Reset();
                }
                var msg = a.Data.Object as ServerMessage;
                if (msg.Name == "Welcome")
                {
                    thisGuid = new Guid(msg.Contents);
                    GUIDReceived?.Invoke(msg.Contents);
                    guidReceiveARE.Set();
                    TerminalBackend.PrefixEnabled = true;
                    TerminalBackend.PrintPrompt();
                }
                else if (msg.Name == "allusers")
                {
                    foreach (var acc in JsonConvert.DeserializeObject <string[]>(msg.Contents))
                    {
                        Console.WriteLine(acc);
                    }
                    TerminalBackend.PrintPrompt();
                }
                else if (msg.Name == "update_your_cp")
                {
                    var args = JsonConvert.DeserializeObject <Dictionary <string, object> >(msg.Contents);
                    if (args["username"] as string == SaveSystem.CurrentUser.Username)
                    {
                        SaveSystem.CurrentSave.Codepoints += (ulong)args["amount"];
                        Desktop.InvokeOnWorkerThread(new Action(() =>
                        {
                            Infobox.Show($"MUD Control Centre", $"Someone bought an item in your shop, and they have paid {args["amount"]}, and as such, you have been granted these Codepoints.");
                        }));
                        SaveSystem.SaveGame();
                    }
                }
                else if (msg.Name == "broadcast")
                {
                    Console.WriteLine(msg.Contents);
                }
                else if (msg.Name == "forward")
                {
                    MessageReceived?.Invoke(JsonConvert.DeserializeObject <ServerMessage>(msg.Contents));
                }
                else if (msg.Name == "Error")
                {
                    var ex = JsonConvert.DeserializeObject <Exception>(msg.Contents);
                    TerminalBackend.PrefixEnabled = true;
                    ConsoleEx.ForegroundColor     = ConsoleColor.Red;
                    ConsoleEx.Bold = true;
                    Console.Write($@"{{MUD_ERROR}}: ");
                    ConsoleEx.Bold            = false;
                    ConsoleEx.Italic          = true;
                    ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine(ex.Message);
                    TerminalBackend.PrefixEnabled = true;
                    TerminalBackend.PrintPrompt();
                }
                else
                {
                    MessageReceived?.Invoke(msg);
                }
            };

            try
            {
                client.Connect(mud_address, port);
            }
            catch (SocketException ex)
            {
                System.Diagnostics.Debug.Print(ex.ToString());
                Initiate(mud_address, port);
            }
        }
コード例 #24
0
        /// <summary>
        /// 打开连接
        /// </summary>
        /// <param name="host">服务器地址</param>
        /// <param name="port">服务器端口号</param>
        /// <param name="userType">用户类型</param>
        /// <param name="userName">用户显示的名称</param>
        /// <param name="userAgent">用户登陆的终端信息</param>
        /// <param name="accessToken">访问令牌</param>
        /// <param name="lastTick">收到最后一条消息的UNIX时间戳</param>
        /// <param name="callback">回调函数</param>
        /// <returns>连接是否成功</returns>
        public bool Connect(string host, int port, string userType, string userName, string userAgent, string accessToken, int lastTick, Action <RequestInfo, ResponseAckInfo> callback)
        {
            var requestInfo = new Message.RequestInfo()
            {
                MsgType = MessageType.Connect,
                //MessageId = TimeStamp.Create(),
                Data = new
                {
                    userType    = userType,
                    userName    = userName,
                    userAgent   = userAgent,
                    accessToken = accessToken,
                    lastTick    = lastTick
                },
                Version = Encrypt_Version
            };
            var preRequestInfo = new Message.RequestInfo()
            {
                MsgType = MessageType.Connect,
                Data    = requestInfo.Data,
                Version = Encrypt_Version
            };

            if (IsAvailable)
            {
                //已经连接成功
                if (callback != null)
                {
                    callback(requestInfo, new ResponseAckInfo()
                    {
                        MsgType = MessageType.Ack, Status = ResponseCode.OK
                    });
                }
                return(true);
            }
            bool result = false;

            //开始连接
            try
            {
                m_Client = new Socket(SocketType.Stream, ProtocolType.Tcp);

                if (EnableEncrypt)
                {
                    requestInfo.Data = EncryptAdapter.Encode(CommonExt.DynamicToJsonString(requestInfo.Data), requestInfo);
                }

                LogOpInfo("BeginConnect:", requestInfo.ToJsonString());
                m_Client.Connect(host, port);
                m_IpAddress = host;
                m_Port      = port;
                if (m_Client.Connected)
                {
                    byte[] sendData = requestInfo.ToByte <Message.RequestInfo>();

                    m_Client.Send(sendData);
                    byte[] bufferData   = new byte[BufferSize];
                    int    receiveLen   = m_Client.Receive(bufferData);
                    byte[] receivedData = bufferData.ToList().GetRange(0, receiveLen).ToArray();
                    var    responseInfo = receivedData.ToObject <Message.ResponseAckInfo>();
                    if (EnableEncrypt)
                    {
                        dynamic deString = CommonCryptoService.Decrypt_DES(responseInfo.Data.ToString(), responseInfo.MessageId);
                        responseInfo.Data = CommonExt.JsonStringToDynamic(deString.ToString());
                    }
                    //LogOpInfo("ConnectOver:", responseInfo.ToJsonString());
                    if (responseInfo.Status == ResponseCode.OK)
                    {
                        m_User.IsAuthenticated    = true;
                        m_User.Name               = userName;
                        m_User.Token              = accessToken;
                        m_User.UserAgent          = userAgent;
                        m_User.UserType           = userType;
                        m_User.AuthenticationType = responseInfo.Data.userPermission;
                        m_User.PermissionList     = Permission.GetUserPermission(m_User.AuthenticationType);
                        //连接使用同步
                        // _sendBuffer.Add(requestInfo);
                        m_LastPingTime = DateTime.Now;

                        //启动线程接收
                        AfterConnectedServer();
                        result            = true;
                        m_IsCanConnecting = true;

                        if (this.clientPingMode == PingMode.Initiative)
                        {
                            _lastSendTime = DateTime.Now;
                            PingTimer.Start();
                        }
                    }
                    else
                    {
                        m_Client.Disconnect(true);
                    }

                    RunUserCallback(callback, preRequestInfo, responseInfo);
                }
            }
            catch (Exception ex)
            {
                LogInfo("ConnectError", ex);
                RunUserCallback(callback, preRequestInfo, new ResponseAckInfo()
                {
                    MsgType = MessageType.Ack, Status = ResponseCode.CLINET_ERR, Data = ex.Message
                });
            }

            return(result);
        }
コード例 #25
0
        private void PingTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            lock (_receivedAckLock)
            {
                if (!ReceivedAck && ActiveNode != null)
                {
                    Debug.WriteLine($"No direct response from Node {ActiveNode.Endpoint}");
                    Logger.LogInformation($"No direct response from Node {ActiveNode.Endpoint}");

                    lock (_nodesLock)
                    {
                        if (Nodes.Count >= 1)
                        {
                            //  Select k num of nodes.
                            RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
                            // Get four random bytes.
                            byte[] four_bytes = new byte[4];
                            provider.GetBytes(four_bytes);

                            // Convert that into an uint.
                            int num = BitConverter.ToInt32(four_bytes, 0);

                            num = num < 0 ? num * -1 : num;

                            int k = 1 + (num % Math.Min(Nodes.Count, 8));

                            //  Create list of node candidates, remove active node.
                            var candidates = Nodes.ToList();
                            candidates.Remove(ActiveNode);

                            //  Shuffle candidates
                            candidates.Shuffle();

                            //  Select k nodes
                            var nodesToPingReq = candidates.Take(k);

                            if (!nodesToPingReq.Any())
                            {
                                Debug.WriteLine("No nodes to select from");
                                Logger.LogInformation("No nodes to select from");
                            }

                            foreach (var node in nodesToPingReq)
                            {
                                Debug.WriteLine($"Sending pingreq for {ActiveNode.Endpoint} to {node.Endpoint}");
                                Logger.LogInformation($"Sending pingreq for {ActiveNode.Endpoint} to {node.Endpoint}");

                                ProtocolProvider.SendMessage(node, new PingReqMessage(PingCorrelationId.Value, ActiveNode, ProtocolProvider.Node));
                            }
                        }
                    }
                }
                else if (ReceivedAck && ActiveNode != null)
                {
                    Debug.WriteLine($"Node {ActiveNode.Endpoint} responded with Ack, marking as alive");
                    Logger.LogInformation($"Node {ActiveNode.Endpoint} responded with Ack, marking as alive");
                }
            }

            PingTimer.Stop();
        }
コード例 #26
0
        static bool RefreshSettings()
        {
            List <string> Sections = GetSections(Path.Combine(Environment.CurrentDirectory, "config.ini"));

            Support.iniManager iniEngine = new Support.iniManager(Path.Combine(Environment.CurrentDirectory, "config.ini"));
            foreach (string item in Sections)
            {
                int NewVersion;
                if (!Int32.TryParse(iniEngine.IniReadValue(item, "Version"), out NewVersion))
                {
                    return(false);
                }
                string EncryptionKey = iniEngine.IniReadValue(item, "EncryptionKey");
                string EncryptionIV  = iniEngine.IniReadValue(item, "EncryptionIV");

                int PingTimer;
                if (!int.TryParse(iniEngine.IniReadValue(item, "PingTimer"), out PingTimer))
                {
                    return(false);
                }

                int LogLevel;
                if (!int.TryParse(iniEngine.IniReadValue(item, "LogLevel"), out LogLevel))
                {
                    return(false);
                }

                if (AppsRunning.Count > 0)
                {
                    int FormerVersion = Classes.CCstData.GetInstance(AppsRunning[0].Application).LatestClientVersion;
                    if (NewVersion != FormerVersion)
                    {
                        Classes.CCstData.GetInstance(AppsRunning[0].Application).LatestClientVersion = NewVersion;
                        Console.WriteLine("CONFIG update: Using now version " + NewVersion.ToString());
                    }

                    int FormerLogLevel = Classes.CCstData.GetInstance(AppsRunning[0].Application).Logger.LogLevel;
                    if (LogLevel != FormerLogLevel)
                    {
                        Classes.CCstData.GetInstance(AppsRunning[0].Application).Logger.LogLevel = LogLevel;
                        Console.WriteLine("CONFIG update: Using now LogLevel " + LogLevel.ToString());
                    }

                    string FormerEncryptionKey = Classes.CCstData.GetInstance(AppsRunning[0].Application).EncryptionKey;
                    if (FormerEncryptionKey != EncryptionKey)
                    {
                        Classes.CCstData.GetInstance(AppsRunning[0].Application).EncryptionKey = EncryptionKey;
                        Console.WriteLine("CONFIG update: Using now encryption key " + EncryptionKey);
                    }

                    string FormerEncryptionIV = Classes.CCstData.GetInstance(AppsRunning[0].Application).EncryptionIV;
                    if (FormerEncryptionIV != EncryptionIV)
                    {
                        Classes.CCstData.GetInstance(AppsRunning[0].Application).EncryptionIV = EncryptionIV;
                        Console.WriteLine("CONFIG update: Using now encryption IV " + EncryptionIV);
                    }

                    int FormerPingTimer = Classes.CCstData.GetInstance(AppsRunning[0].Application).PingTimer;
                    if (FormerEncryptionIV != EncryptionIV)
                    {
                        Classes.CCstData.GetInstance(AppsRunning[0].Application).PingTimer = PingTimer;
                        Console.WriteLine("CONFIG update: Using now PingTimer " + PingTimer.ToString() + "ms");
                    }
                }
            }
            return(true);
        }
コード例 #27
0
ファイル: Pinger.cs プロジェクト: Unity-Technologies/MGOBE
 public void Stop()
 {
     PingTimer.Close();
     PongTimer.Close();
 }
コード例 #28
0
ファイル: Connection.cs プロジェクト: isaveu/uwp-multiplayer
        private async void ParsePacket(Packet packet)
        {
            if (packet.payload == null)
            {
                Game.Log("Packet Received (" + packet.commandType + ").");
            }
            else if (packet.commandType == Packets.PingRequest && packet.commandType == Packets.PingReply && packet.commandType == Packets.PlayerPing &&
                     packet.commandType != Packets.Position && packet.commandType != Packets.PlayerPosition)
            {
                Game.Log("Packet Received (" + packet.commandType + ") " + ByteArray2String(packet.payload) + ".");
            }

            if (packet.commandType == 0 && host)
            {
                // <Host>
                // Ping request from player
                Game.Log("Ping test request received.");

                Tuple <short, byte[]> pingReplyPacket = CreatePacket(Packets.PingTestReply, null);
                await SendPacket(pingReplyPacket);

                this.Close();
            }
            else if (packet.commandType == 1)
            {
                // <Player>
                // Ping reply from host

                PingTimer.Stop();
                connected = false;

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PingTestReplyReceivedEvent?.Invoke(null, new PingTestReplyArguments(
                                                           StreamSocket.Information.RemoteAddress.ToString(),
                                                           Int32.Parse(StreamSocket.Information.RemotePort),
                                                           PingTimer.ElapsedMilliseconds
                                                           ));
                });
            }
            else if (packet.commandType == 2 && host)
            {
                // <Host>
                // Join request from player

                byte[] playerIdBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, packet.payload.Length);
                PlayerId = Encoding.UTF8.GetString(playerIdBytes);

                Game.Log("Join request from player (" + PlayerId + ").");

                // Code
                ushort code = 0;

                // Check if player id
                // is used
                if (Game.PlayerId == PlayerId)
                {
                    code = 1;
                }
                else
                {
                    for (int i = 0; i < server.Connections.Count; i++)
                    {
                        Connection connection = server.Connections[i];

                        if (connection.PlayerId == PlayerId)
                        {
                            code = 1;
                        }
                    }
                }

                if (code == 1)
                {
                    Game.Log("Join request from player (" + PlayerId + ") rejected, player id used.");
                }

                // Check if maximum number of players
                // is exceeded
                if (server.Connections.Count == 16)
                {
                    code = 2;
                    Game.Log("Join request from player (" + PlayerId + ") rejected, no slots available.");
                }

                // Check if host
                // left
                if (Game.State == States.Started)
                {
                    code = 3;
                    Game.Log("Join request from player (" + PlayerId + ") rejected, match is deleted.");
                }

                // Send reply
                byte[] joinReplyPayload        = new byte[19];
                byte[] hostPlayerIdPaddedBytes = new byte[15];

                byte[] codeBytes = BitConverter.GetBytes(code);

                byte[] hostPlayerIdBytes = Encoding.ASCII.GetBytes(Game.PlayerId);
                System.Buffer.BlockCopy(hostPlayerIdBytes, 0, hostPlayerIdPaddedBytes, 0, hostPlayerIdBytes.Length);

                ushort hostReadyStatus = 0;

                if (Game.Ready)
                {
                    hostReadyStatus = 1;
                }

                byte[] readyStatusBytes = BitConverter.GetBytes(hostReadyStatus);

                System.Buffer.BlockCopy(codeBytes, 0, joinReplyPayload, 0, codeBytes.Length);
                System.Buffer.BlockCopy(hostPlayerIdPaddedBytes, 0, joinReplyPayload, codeBytes.Length, hostPlayerIdPaddedBytes.Length);
                System.Buffer.BlockCopy(readyStatusBytes, 0, joinReplyPayload,
                                        codeBytes.Length + hostPlayerIdPaddedBytes.Length,
                                        readyStatusBytes.Length);

                Tuple <short, byte[]> joinReplyPacket = CreatePacket(Packets.JoinReply, joinReplyPayload);
                await SendPacket(joinReplyPacket);

                if (code > 0)
                {
                    this.Close();
                    return;
                }

                if (Game.State == States.MatchEnded || Game.State == States.CleanupMatchDetails1 || Game.State == States.CleanupMatchDetails2)
                {
                    CleanupCompleted = true;
                    server.PlayerCleanupCompleted(this);
                }

                // Send player list
                Game.Log("Sending player list to player (" + PlayerId + ").");
                server.SendPlayerList(this);

                // Broadcast to all players
                byte[] playerJoinedPayload = Encoding.ASCII.GetBytes(PlayerId);
                Tuple <short, byte[]> playerJoinedPacket = server.CreatePacket(Packets.PlayerJoined, playerJoinedPayload);
                await server.SendPacket(playerJoinedPacket);

                // Send match state
                byte[] statePayload = BitConverter.GetBytes(Game.State);
                Tuple <short, byte[]> statePacket = CreatePacket(Packets.GameState, statePayload);
                await SendPacket(statePacket);

                // Add to connections list
                server.PlayerJoined(this);

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerJoinedEvent?.Invoke(this, new PlayerJoinedArguments(PlayerId, false, Ready));
                });

                // Request ping every second
                PingTimer         = new Stopwatch();
                pingInterval      = new Timer(SendPing, null, 0, 1000);
                pingReplyReceived = true;

                Joined = true;
            }
            else if (packet.commandType == 3)
            {
                // <Player>
                // Join reply from host

                byte[] codeBytes = new byte[2];
                System.Buffer.BlockCopy(packet.payload, 0, codeBytes, 0, 2);
                ushort code = BitConverter.ToUInt16(codeBytes, 0);

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    JoinMatchEvent?.Invoke(null, new JoinMatchArguments(
                                               code
                                               ));
                });

                if (code > 0)
                {
                    this.Close();
                    return;
                }
                else
                {
                    byte[] playerIdBytes    = new byte[15];
                    byte[] playerReadyBytes = new byte[2];

                    System.Buffer.BlockCopy(packet.payload, codeBytes.Length, playerIdBytes, 0, playerIdBytes.Length);
                    System.Buffer.BlockCopy(packet.payload, codeBytes.Length + playerIdBytes.Length, playerReadyBytes, 0, playerReadyBytes.Length);

                    PlayerId = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                    Joined   = true;

                    ushort playerStatus = BitConverter.ToUInt16(playerReadyBytes, 0);
                    bool   playerReady  = false;

                    if (playerStatus == 1)
                    {
                        playerReady = true;
                    }

                    // Check ping every second
                    PingTimer = new Stopwatch();
                    PingTimer.Start();
                    pingInterval = new Timer(CheckPing, null, 0, 1000);

                    // Update UI
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        PlayerJoinedEvent?.Invoke(this, new PlayerJoinedArguments(PlayerId, true, playerReady));
                    });
                }
            }
            else if (packet.commandType == 4)
            {
                // <Player>
                // Game state from host

                byte[] stateBytes = new byte[2];
                System.Buffer.BlockCopy(packet.payload, 0, stateBytes, 0, stateBytes.Length);

                ushort state = BitConverter.ToUInt16(stateBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MatchStateEvent?.Invoke(null, new MatchStateArguments(
                                                state
                                                ));
                });
            }
            else if (packet.commandType == 5)
            {
                // <Host/Player>
                // Leave request from host/player

                leaveRequestReceived = true;

                if (host)
                {
                    // Broadcast to all players
                    byte[] playerLeftPayload = Encoding.ASCII.GetBytes(PlayerId);
                    Tuple <short, byte[]> playerLeftPacket = server.CreatePacket(Packets.PlayerLeft, playerLeftPayload);
                    await server.SendPacket(playerLeftPacket);
                }

                // Stop ping interval
                if (pingInterval != null)
                {
                    pingInterval.Dispose();
                }

                // Remove from connections list
                server.PlayerLeft(this);

                // Update player list and UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerLeftEvent?.Invoke(this, new PlayerLeftArguments(PlayerId, false));
                });

                // Disconnect player
                Tuple <short, byte[]> leaveReplyPacket = CreatePacket(Packets.LeaveReply, null);
                await SendPacket(leaveReplyPacket);

                this.Close();
            }
            else if (packet.commandType == 6)
            {
                // <Host/Player>
                // Leave reply from host/player

                LeaveRequestAccepted = true;

                if (host)
                {
                    Game.Log("Player (" + PlayerId + ") accepted the leave request.");
                }
                else
                {
                    Game.Log("Host accepted the leave request.");
                }

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    LeaveReplyEvent.Invoke(null);
                });
            }
            else if (packet.commandType == 7)
            {
                // <Player>
                // Ping request from host

                Tuple <short, byte[]> pingReplyPacket = CreatePacket(Packets.PingReply, null);
                await SendPacket(pingReplyPacket);

                if (PingTimer != null)
                {
                    PingTimer.Restart();
                }
            }
            else if (packet.commandType == 8 && host)
            {
                // <Host>
                // Ping reply from player

                PingTimer.Stop();
                PingTime = (ulong)PingTimer.ElapsedMilliseconds;

                pingReplyReceived = true;

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerPingEvent?.Invoke(this, new PlayerPingArguments(PlayerId, PingTime));
                });

                // Send to all players
                byte[] playerPingTimePayload = new byte[23];
                byte[] playerIdPaddedBytes   = new byte[15];

                byte[] playerIdBytes       = Encoding.ASCII.GetBytes(PlayerId);
                byte[] playerPingTimeBytes = BitConverter.GetBytes(PingTime);

                System.Buffer.BlockCopy(playerIdBytes, 0, playerIdPaddedBytes, 0, playerIdBytes.Length);

                System.Buffer.BlockCopy(playerIdPaddedBytes, 0, playerPingTimePayload, 0, playerIdPaddedBytes.Length);
                System.Buffer.BlockCopy(playerPingTimeBytes, 0, playerPingTimePayload, playerIdPaddedBytes.Length, playerPingTimeBytes.Length);

                Tuple <short, byte[]> playerPingTimePacket = server.CreatePacket(Packets.PlayerPing, playerPingTimePayload);
                await server.SendPacket(playerPingTimePacket);
            }
            else if (packet.commandType == 9)
            {
                // <Player>
                // Player from list

                byte[] playerIdBytes = new byte[15];
                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, 15);
                string playerId = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);

                byte[] playerReadyStatusBytes = new byte[2];
                System.Buffer.BlockCopy(packet.payload, 15, playerReadyStatusBytes, 0, 2);
                ushort playerReadyStatus = BitConverter.ToUInt16(playerReadyStatusBytes, 0);

                bool playerReady = false;

                if (playerReadyStatus == 1)
                {
                    playerReady = true;
                }

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerJoinedEvent?.Invoke(this, new PlayerJoinedArguments(playerId, false, playerReady));
                });
            }
            else if (packet.commandType == 10)
            {
                // <Player>
                // Player joined

                byte[] playerIdBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, packet.payload.Length);
                string playerId = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerJoinedEvent?.Invoke(this, new PlayerJoinedArguments(playerId, false, false));
                });
            }
            else if (packet.commandType == 11)
            {
                // <Player>
                // Player left

                byte[] playerIdBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, packet.payload.Length);
                string playerId = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerLeftEvent?.Invoke(this, new PlayerLeftArguments(playerId, false));
                });
            }
            else if (packet.commandType == 12)
            {
                // <Player>
                // Ready time left

                byte[] readyTimeLeftBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, readyTimeLeftBytes, 0, 4);

                uint readyTimeLeft = BitConverter.ToUInt32(readyTimeLeftBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    ReadyTimeEvent?.Invoke(null, new ReadyTimeLeftArguments(readyTimeLeft));
                });
            }
            else if (packet.commandType == 13)
            {
                // <Player>
                // Player ping time

                byte[] playerIdBytes       = new byte[15];
                byte[] playerPingTimeBytes = new byte[8];

                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, 15);
                System.Buffer.BlockCopy(packet.payload, 15, playerPingTimeBytes, 0, 8);

                string playerId       = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                ulong  playerPingTime = BitConverter.ToUInt64(playerPingTimeBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerPingEvent?.Invoke(null, new PlayerPingArguments(playerId, playerPingTime));
                });
            }
            else if (packet.commandType == 14 && host)
            {
                // <Host>
                // Player ready

                byte[] readyStatusBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, readyStatusBytes, 0, packet.payload.Length);
                ushort readyStatus = BitConverter.ToUInt16(readyStatusBytes, 0);

                if (readyStatus == 0)
                {
                    Ready = false;
                }
                else
                {
                    Ready = true;
                }

                // Broadcast to all players
                byte[] playerStatusPayload    = new byte[17];
                byte[] playerIdPaddedBytes    = new byte[15];
                byte[] playerIdBytes          = Encoding.ASCII.GetBytes(PlayerId);
                byte[] playerReadyStatusBytes = BitConverter.GetBytes(readyStatus);

                System.Buffer.BlockCopy(playerIdBytes, 0, playerIdPaddedBytes, 0, playerIdBytes.Length);

                System.Buffer.BlockCopy(playerIdPaddedBytes, 0, playerStatusPayload, 0, playerIdPaddedBytes.Length);
                System.Buffer.BlockCopy(playerReadyStatusBytes, 0, playerStatusPayload, playerIdPaddedBytes.Length, playerReadyStatusBytes.Length);

                Tuple <short, byte[]> playeReadyStatusPacket = server.CreatePacket(Packets.PlayerReady, playerStatusPayload);
                await server.SendPacket(playeReadyStatusPacket);

                // Update ready state
                server.PlayerReady(this);

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerReadyEvent?.Invoke(null, new PlayerReadyArguments(PlayerId, Ready));
                });
            }
            else if (packet.commandType == 15)
            {
                // <Player>
                // Player ready

                byte[] playerIdBytes          = new byte[15];
                byte[] playerReadyStatusBytes = new byte[2];

                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, 15);
                System.Buffer.BlockCopy(packet.payload, 15, playerReadyStatusBytes, 0, 2);

                string playerId          = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                ushort playerReadyStatus = BitConverter.ToUInt16(playerReadyStatusBytes, 0);

                bool ready = false;

                if (playerReadyStatus == 1)
                {
                    ready = true;
                }

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerReadyEvent?.Invoke(null, new PlayerReadyArguments(playerId, ready));
                });
            }
            else if (packet.commandType == 16)
            {
                // <Player>
                // Load map

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    LoadMapEvent?.Invoke(null);
                });
            }
            else if (packet.commandType == 17)
            {
                // <Player>
                // Map objects created

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MapObjectsCreatedEvent?.Invoke(null);
                });
            }
            else if (packet.commandType == 18 && host)
            {
                // <Host>
                // Map objects requested

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerMapObjectsRequestedEvent?.Invoke(this);
                });
            }
            else if (packet.commandType == 19)
            {
                // <Player>
                // Target position

                byte[] targetXBytes = new byte[4];
                byte[] targetYBytes = new byte[4];

                System.Buffer.BlockCopy(packet.payload, 0, targetXBytes, 0, 4);
                System.Buffer.BlockCopy(packet.payload, targetXBytes.Length, targetYBytes, 0, 4);

                float targetX = BitConverter.ToSingle(targetXBytes, 0);
                float targetY = BitConverter.ToSingle(targetYBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    TargetPositionEvent?.Invoke(null, new TargetPositionArguments(targetX, targetY));
                });
            }
            else if (packet.commandType == 20)
            {
                // <Player>
                // Score

                byte[] playerIdBytes = new byte[15];
                byte[] scoreBytes    = new byte[2];

                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, 15);
                System.Buffer.BlockCopy(packet.payload, playerIdBytes.Length, scoreBytes, 0, scoreBytes.Length);

                string playerId = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                ushort score    = BitConverter.ToUInt16(scoreBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerScoreEvent?.Invoke(null, new PlayerScoreArguments(playerId, score));
                });
            }
            else if (packet.commandType == 21)
            {
                // <Player>
                // Map data end

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MapDataEndEvent?.Invoke(null);
                });
            }
            else if (packet.commandType == 22 && host)
            {
                // <Host>
                // Player map loaded

                if (!MapLoaded)
                {
                    MapLoaded = true;
                    server.PlayerMapLoaded(this);
                }
            }
            else if (packet.commandType == 23)
            {
                // <Player>
                // Show map

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    ShowMapEvent?.Invoke(this);
                });
            }
            else if (packet.commandType == 24 && host)
            {
                // <Host>
                // Player map shown

                if (!MapShown)
                {
                    MapShown = true;
                    server.PlayerMapShown(this);
                }
            }
            else if (packet.commandType == 25)
            {
                // <Player>
                // Match countdown

                byte[] countdownBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, countdownBytes, 0, 4);

                uint countdownSeconds = BitConverter.ToUInt32(countdownBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MatchCountdownEvent?.Invoke(this, new MatchCountdownArguments(countdownSeconds));
                });
            }
            else if (packet.commandType == 26)
            {
                // <Player>
                // Match started

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MatchStartedEvent?.Invoke(this);
                });
            }
            else if (packet.commandType == 27 && host)
            {
                // <Host>
                // Player position

                byte[] playerXBytes1     = new byte[4];
                byte[] playerYBytes1     = new byte[4];
                byte[] playerAngleBytes1 = new byte[4];

                System.Buffer.BlockCopy(packet.payload, 0, playerXBytes1, 0, 4);
                System.Buffer.BlockCopy(packet.payload, playerXBytes1.Length, playerYBytes1, 0, 4);
                System.Buffer.BlockCopy(packet.payload, playerXBytes1.Length + playerYBytes1.Length, playerAngleBytes1, 0, 4);

                PlayerX     = BitConverter.ToSingle(playerXBytes1, 0);
                PlayerY     = BitConverter.ToSingle(playerYBytes1, 0);
                PlayerAngle = BitConverter.ToSingle(playerAngleBytes1, 0);

                // Broadcast to all players
                byte[] positionPayload     = new byte[27];
                byte[] playerIdPaddedBytes = new byte[15];

                byte[] playerIdBytes = Encoding.ASCII.GetBytes(PlayerId);
                byte[] playerX       = BitConverter.GetBytes(PlayerX);
                byte[] playerY       = BitConverter.GetBytes(PlayerY);
                byte[] playerAngle   = BitConverter.GetBytes(PlayerAngle);

                System.Buffer.BlockCopy(playerIdBytes, 0, playerIdPaddedBytes, 0, playerIdBytes.Length);

                System.Buffer.BlockCopy(playerIdPaddedBytes, 0, positionPayload, 0, playerIdPaddedBytes.Length);
                System.Buffer.BlockCopy(playerX, 0, positionPayload, playerIdPaddedBytes.Length, playerX.Length);
                System.Buffer.BlockCopy(playerY, 0, positionPayload, playerIdPaddedBytes.Length + playerX.Length, playerY.Length);
                System.Buffer.BlockCopy(playerAngle, 0, positionPayload, playerIdPaddedBytes.Length + playerX.Length + playerY.Length, playerAngle.Length);

                Tuple <short, byte[]> playerPositionPacket = server.CreatePacket(Packets.PlayerPosition, positionPayload);
                await server.SendPacket(playerPositionPacket);

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerPositionEvent?.Invoke(null, new PlayerPositionArguments(PlayerId, PlayerX, PlayerY, PlayerAngle));
                });
            }
            else if (packet.commandType == 28)
            {
                // <Player>
                // Player position

                byte[] playerIdBytes    = new byte[15];
                byte[] playerXBytes     = new byte[4];
                byte[] playerYBytes     = new byte[4];
                byte[] playerAngleBytes = new byte[4];

                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, 15);
                System.Buffer.BlockCopy(packet.payload, playerIdBytes.Length, playerXBytes, 0, playerXBytes.Length);
                System.Buffer.BlockCopy(packet.payload, playerIdBytes.Length + playerXBytes.Length, playerYBytes, 0, playerYBytes.Length);
                System.Buffer.BlockCopy(packet.payload, playerIdBytes.Length + playerXBytes.Length + playerYBytes.Length, playerAngleBytes, 0, playerAngleBytes.Length);

                string playerId    = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                float  playerX     = BitConverter.ToSingle(playerXBytes, 0);
                float  playerY     = BitConverter.ToSingle(playerYBytes, 0);
                float  playerAngle = BitConverter.ToSingle(playerAngleBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerPositionEvent?.Invoke(null, new PlayerPositionArguments(playerId, playerX, playerY, playerAngle));
                });
            }
            else if (packet.commandType == 29)
            {
                // <Player>
                // Match time left

                byte[] timeLeftBytes = new byte[packet.payload.Length];
                System.Buffer.BlockCopy(packet.payload, 0, timeLeftBytes, 0, 4);

                uint timeLeftSeconds = BitConverter.ToUInt32(timeLeftBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MatchTimeLeftEvent?.Invoke(null, new MatchTimeLeftArguments(timeLeftSeconds));
                });
            }
            else if (packet.commandType == 30 && host)
            {
                // <Host>
                // Target reached

                TargetIndex++;

                // Sent to all players
                byte[] targetReachedPayload = new byte[17];
                byte[] playerIdPaddedBytes  = new byte[15];

                byte[] playerIdBytes = Encoding.ASCII.GetBytes(PlayerId);
                byte[] targetIndex   = BitConverter.GetBytes(TargetIndex);

                System.Buffer.BlockCopy(playerIdBytes, 0, playerIdPaddedBytes, 0, playerIdBytes.Length);

                System.Buffer.BlockCopy(playerIdPaddedBytes, 0, targetReachedPayload, 0, playerIdPaddedBytes.Length);
                System.Buffer.BlockCopy(targetIndex, 0, targetReachedPayload, playerIdPaddedBytes.Length, targetIndex.Length);

                Tuple <short, byte[]> targetReachedPacket = server.CreatePacket(Packets.PlayerTargetReached, targetReachedPayload);
                await server.SendPacket(targetReachedPacket);

                // Update UI
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerTargetReachedEvent?.Invoke(null, new PlayerTargetReachedArguments(PlayerId, TargetIndex));
                });
            }
            else if (packet.commandType == 31)
            {
                // <Player>
                // Target reached

                byte[] playerIdBytes          = new byte[15];
                byte[] playerTargetIndexBytes = new byte[2];

                System.Buffer.BlockCopy(packet.payload, 0, playerIdBytes, 0, playerIdBytes.Length);
                System.Buffer.BlockCopy(packet.payload, playerIdBytes.Length, playerTargetIndexBytes, 0, playerTargetIndexBytes.Length);

                string playerId          = Encoding.UTF8.GetString(playerIdBytes).Replace("\0", String.Empty);
                ushort playerTargetIndex = BitConverter.ToUInt16(playerTargetIndexBytes, 0);

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    PlayerTargetReachedEvent?.Invoke(null, new PlayerTargetReachedArguments(playerId, playerTargetIndex));
                });
            }
            else if (packet.commandType == 32)
            {
                // <Player>
                // Match ended

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    MatchEndedEvent?.Invoke(this);
                });
            }
            else if (packet.commandType == 33)
            {
                // <Player>
                // Load match details

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    LoadMatchDetailsEvent?.Invoke(this);
                });
            }
            else if (packet.commandType == 34 && host)
            {
                // <Host>
                // Cleanup completed

                if (!CleanupCompleted)
                {
                    CleanupCompleted = true;
                    server.PlayerCleanupCompleted(this);
                }
            }
            else if (packet.commandType == 35)
            {
                // <Player>
                // Show match details

                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                {
                    ShowMatchDetailsEvent?.Invoke(this);
                });
            }
        }