public override void DataReceived ( NetCommand command, NetIncomingMessage msg )
			{
				if (command==NetCommand.Snapshot) {
					
					var frame		=	msg.ReadUInt32();
					var prevFrame	=	msg.ReadUInt32();
					var ackCmdID	=	msg.ReadUInt32();
					var serverTicks	=	msg.ReadInt64();
					var size		=	msg.ReadInt32();

					//Log.Warning("{0}", offsetTicks );

					if (prevFrame!=0) {
						Log.Warning("Bad initial snapshot. Previous frame does not equal zero.");
						return;
					}
					if (ackCmdID!=0) {
						Log.Warning("Bad command ID {0}. Command ID for initial snapshot must be zero.", ackCmdID);
						return;
					}

					//	read snapshot :
					var snapshot	=	NetDeflate.Decompress( msg.ReadBytes(size) );

					//	initial snapshot contains atom table :
					gameClient.Atoms	=	new AtomCollection( msg );


					gameClient.SetState( new Active( gameClient, frame, snapshot, serverTicks ) );
				}

				if (command==NetCommand.Notification) {
					gameClient.FeedNotification( msg.ReadString() );
				}
			}
Esempio n. 2
0
            /// <summary>
            /// Sets writing state
            /// </summary>
            /// <param name="state"></param>
            private void SetWritingState(bool state)
            {
                if (_State == state)
                {
                    return;
                }

                _State = state;

                NetCommand command = new NetCommand();

                command.Name = CommandNames.INFORM_WRITING_STATE;
                command.Parameters.Add(new ParameterString("un", _Form.TargetUser));
                command.Parameters.Add(new ParameterBoolean("st", state));
                _Form._SessionManager.AddCommand(command);
            }
        public static void run()
        {
            while (running)
            {
                if (loggedin && Server.Connected)
                {
                    NetCommand command = NetHelper.ReadNetCommand(Server);
                    HandleNetCommand(command);
                }
            }

            if (Server != null)
            {
                Server.Close();
            }
        }
Esempio n. 4
0
        public static void run()
        {
            while (running)
            {
                if (Doctor.Connected)
                {
                    NetCommand command = NetHelper.ReadNetCommand(Doctor);
                    ParseCommand(command);
                }
            }

            if (Doctor != null)
            {
                Doctor.Close();
            }
        }
Esempio n. 5
0
        public bool Send(NetCommand command)
        {
            NetSession sessionReceiver = m_sessionMgr.FindSession(command.SessionID);

            if (null == sessionReceiver)
            {
                return(false);
            }

            if (sessionReceiver.Send(command.Buffer, command.BufferSize) == false)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Applies innner operation
        /// </summary>
        protected override void DoOperation()
        {
            var un = new ParameterString("un", Client.Username);

            for (int i = 0; i < Server.Clients.Count; i++)
            {
                if (Server.Clients[i] != Client)
                {
                    var command = new NetCommand(CommandNames.CLIENT_UPDATE_PICTURE);
                    command.Parameters.Add(un);

                    Server.Clients[i].Commands.Add(command);
                }
            }

            Response = new NetResponse(true);
        }
Esempio n. 7
0
        private void Process(NetCommand message)
        {
            if (message is ServerNotAvailableCommand)
            {
                ServerNotAvailableInner(((ServerNotAvailableCommand)message).Server);
            }

            if (message is OperationCompleteCommand)
            {
                CompleteOperation((message as OperationCompleteCommand).Transaction);
            }

            if (message is ReadOperationCompleteCommand)
            {
                CompleteOperation((message as ReadOperationCompleteCommand).Data);
            }
        }
Esempio n. 8
0
        private bool OnConnected(NetCommand command)
        {
            UInt64 nSessionID;
            bool   bIsSuccess;

            if (command.ReadUInt64(out nSessionID) == false)
            {
                return(false);
            }
            if (command.ReadBoolean(out bIsSuccess) == false)
            {
                return(false);
            }

            m_refServerMonitorClient.OnConnectedMachine(nSessionID, bIsSuccess);
            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// Sets given command to the server
        /// </summary>
        /// <param name="command"></param>
        public void Send(NetCommand command)
        {
            if (SocketStatus != SocketStatus.Connected)
            {
                return;
            }
            command.Status = CommandStatus.SendingToTarget;
            using (MemoryStream str = new MemoryStream(0))
            {
                BinaryWriter writer = new BinaryWriter(str, System.Text.Encoding.Unicode);
                command.Write(writer);
                writer.Flush();

                Send(str.ToArray(), 0, command.Id);
            }
            command.Status = CommandStatus.WaitingForResponse;
        }
Esempio n. 10
0
        /// <summary>
        /// Applies operation
        /// </summary>
        protected override void DoOperation()
        {
            var uname = Command.Parameters["un"] as ParameterString;

            for (int i = 0; i < Server.Clients.Count; i++)
            {
                if (Server.Clients[i].Username == uname.Value)
                {
                    Response = new NetResponse(false, "This username is already in use");
                    return;
                }
            }

            Client.Username = uname.Value;
            Client.Status   = ClientStatus.Active;

            Response = new NetResponse(true, "User logged in");

            // send other users that this user is online now ..
            for (int i = 0; i < Server.Clients.Count; i++)
            {
                if (Server.Clients[i] == Client)
                {
                    continue;
                }

                NetCommand command = new NetCommand(CommandNames.U_LOGIN);
                command.Parameters.Add(new ParameterInt32("hash", Client.HashCode));
                command.Parameters.Add(new ParameterInt32("st", Convert.ToInt32(Client.Status)));
                command.Parameters.Add(uname);

                Server.Clients[i].Commands.Add(command);


                if (Server.Clients[i].Status != ClientStatus.None)
                {
                    NetCommand command2 = new NetCommand(CommandNames.U_LOGIN);
                    command2.Parameters.Add(new ParameterInt32("hash", Server.Clients[i].HashCode));
                    command2.Parameters.Add(new ParameterInt32("st", Convert.ToInt32(Server.Clients[i].Status)));
                    command2.Parameters.Add(new ParameterString("un", Server.Clients[i].Username));

                    Client.Commands.Add(command2);
                }
            }
        }
        private bool OnMonitoringLog(NetCommand command)
        {
            string[] arrServerName = new string[1];

            if (command.ReadString(out arrServerName[0]) == false)
            {
                return(false);
            }

            UInt64 nSessionID = command.SessionID;

            if (m_refCommandSender.SendRequestServerInfo(nSessionID, arrServerName) == false)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        //解码
        protected override NetCommand DecodeCmd(uint pid, MemoryStream payloadStream)
        {
            NetCommand cmd = null;
            // 根据pid找到对应的消息对象
            var msgType = Registry.Find((uint)pid);

            if (msgType == null)
            {
                cmd = new ByteNetCommand {
                    pid = (uint)pid, buf = payloadStream.ToArray()
                };
            }
            else
            {
                cmd = ProtoBuf.Serializer.Deserialize(msgType, payloadStream) as NetCommand;
            }
            return(cmd);
        }
Esempio n. 13
0
        private static void HandToClient(NetCommand command)
        {
            bool handled = false;

            foreach (ClientThread cl in clients)
            {
                if (cl.Session == command.Session)
                {
                    cl.HandleCommand(command);
                    handled = true;
                }
            }

            if (!handled)
            {
                backlog.Add(command);
            }
        }
Esempio n. 14
0
        public void Update()
        {
            while (true)
            {
                NetCommand command = m_commandQueue.PopCommand();
                if (command == null)
                {
                    break;
                }

                if (m_refCommandHandler.OnCommand(command) == false)
                {
                    FileLog.Instance.Write("Error! Command 처리 오류. ID={0}", command.CommandID);
                }
            }

            m_sessionMgr.Update();
        }
Esempio n. 15
0
        public bool OnGetServerInfoReq(NetCommand command)
        {
            byte nServerNameCount;

            string[] arrServerNames;

            if (command.ReadByte(out nServerNameCount) == false)
            {
                return(false);
            }

            arrServerNames = new string[nServerNameCount];
            for (int i = 0; i < nServerNameCount; ++i)
            {
                if (command.ReadString(out arrServerNames[i]) == false)
                {
                    return(false);
                }
            }


            TRANS_SERVERINFONODE        serverInfo     = new TRANS_SERVERINFONODE();
            List <TRANS_SERVERINFONODE> listServerInfo = new List <TRANS_SERVERINFONODE>();

            for (int i = 0; i < nServerNameCount; ++i)
            {
                if (m_refServerMonitor.refServerInfoMgr.GetTRANS_SERVERINFONODE(arrServerNames[i], ref serverInfo) == false)
                {
                    continue;
                }

                listServerInfo.Add(serverInfo);
            }

            TRANS_SERVERINFONODE[] arrServerInfo = new TRANS_SERVERINFONODE[listServerInfo.Count];
            listServerInfo.CopyTo(arrServerInfo);

            if (m_refCommandSender.SendGetServerInfoRes(command.SessionID, ref arrServerInfo) == false)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 16
0
        public bool SendGetServerInfoRes(UInt64 nSessionID, ref TRANS_SERVERINFONODE[] arrServerInfo)
        {
            NetCommand commandSend = new NetCommand(nSessionID, CMD.GET_SERVERINFO_RES);

            if (commandSend.WriteByte((byte)arrServerInfo.Length) == false)
            {
                return(false);
            }
            for (int i = 0; i < arrServerInfo.Length; ++i)
            {
                if (commandSend.WriteString(arrServerInfo[i].strServerName) == false)
                {
                    return(false);
                }
                if (commandSend.WriteByte((byte)arrServerInfo[i].nProcessState) == false)
                {
                    return(false);
                }
                if (commandSend.WriteByte((byte)arrServerInfo[i].nServableState) == false)
                {
                    return(false);
                }
                if (commandSend.WriteBoolean(arrServerInfo[i].bRevivable) == false)
                {
                    return(false);
                }
                if (commandSend.WriteInt32(arrServerInfo[i].nCurServerPlayerCount) == false)
                {
                    return(false);
                }
            }

            if (commandSend.MakingComplete() == false)
            {
                return(false);
            }

            if (m_refNetServer.Send(commandSend) == false)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 17
0
        private void OnSocketAsyncReceiveFinish(IAsyncResult result)
        {
            SocketReceiveStateObject stateObj = (SocketReceiveStateObject)result.AsyncState;
            Socket socket    = stateObj.socket;
            int    readBytes = 0;

            try
            {
                readBytes = socket.EndReceive(result);
            }
            catch (ObjectDisposedException)
            {
                return;
            }
            catch (Exception e)
            {
                NetEvent evt = this.netEventPool.GetObject();
                evt.type = NetEventType.NetWorkError;
                evt.data = e.Message;
                NetCommand cmd = this.netCommandPool.GetObject();
                cmd.type = NetCommandType.NetEventProxy;
                cmd.data = evt;
                this.netCommandQueue.Enqueue(cmd);
                return;
            }
            if (readBytes == 0)
            {
                NetEvent evt = this.netEventPool.GetObject();
                evt.type = NetEventType.PeerClose;
                NetCommand cmd = this.netCommandPool.GetObject();
                cmd.type = NetCommandType.NetEventProxy;
                cmd.data = evt;
                this.netCommandQueue.Enqueue(cmd);
            }
            else
            {
                NetEvent evt = this.netEventPool.GetObject();
                evt.type = NetEventType.RecvMessage;
                evt.data = new byte[readBytes];
                Buffer.BlockCopy(stateObj.buffer, 0, (byte[])evt.data, 0, readBytes);
                this.netEventQueue.Enqueue(evt);
                socket.BeginReceive(stateObj.buffer, 0, stateObj.buffer.Length, SocketFlags.None, OnSocketAsyncReceiveFinish, stateObj);
            }
        }
Esempio n. 18
0
        private void InvokeUserStatusChanged(object sender, EventArgs e)
        {
            NetCommand command = sender as NetCommand;

            if (command == null)
            {
                return;
            }

            ParameterInt32 hash = command.Parameters["hash"]
                                  as ParameterInt32;
            ParameterInt32 st = command.Parameters["st"]
                                as ParameterInt32;
            ClientStatus cst = (ClientStatus)st.Value;

            for (int i = 0; i < lvwUsers.Items.Count; i++)
            {
                if (hash.Value.Equals(lvwUsers.Items[i].Tag))
                {
                    switch (cst)
                    {
                    case ClientStatus.Active:
                        lvwUsers.Items[i].ImageIndex = 2;
                        break;

                    case ClientStatus.OutToLunch:
                        lvwUsers.Items[i].ImageIndex = 1;
                        break;

                    case ClientStatus.StandBy:
                        lvwUsers.Items[i].ImageIndex = 0;
                        break;

                    case ClientStatus.Waiting:
                        lvwUsers.Items[i].ImageIndex = 3;
                        break;
                    }
                    break;
                }
            }

            command.Response = new NetResponse(true);
        }
Esempio n. 19
0
        public RemoteResult SendSyncToDistributor(ServerId server, NetCommand command)
        {
            var connection = FindServer(server) as SingleConnectionToDistributor;

            if (connection == null)
            {
                ConnectToWriter(server);
                connection = FindServer(server) as SingleConnectionToDistributor;
            }

            if (connection == null)
            {
                Logger.Logger.Instance.DebugFormat("CollectorNetModule: process server not found  server = {0}", server);
                _distributor.ServerUnavailable(server);
                return(new ServerNotAvailable(server));
            }

            return(connection.SendSync(command));
        }
Esempio n. 20
0
        private void OnGetPicture(NetCommand command)
        {
            if (client1.ImagePath != string.Empty &&
                System.IO.File.Exists(client1.ImagePath))
            {
                command.Response = new NetResponse(true);

                FileStream str  = File.Open(client1.ImagePath, FileMode.Open);
                byte[]     temp = new byte[str.Length];
                str.Read(temp, 0, temp.Length);

                ParameterByteArray a = new ParameterByteArray("img", temp);
                command.Response.Parameters.Add(a);
            }
            else
            {
                command.Response = new NetResponse(false, "No picture");
            }
        }
        public void HandleCommand(NetCommand command)
        {
            switch (command.Type)
            {
            case NetCommand.CommandType.DATA:
                lock (Metingen)
                {
                    Metingen.Add(command.Meting);
                }
                window.Invoke(window.updateMetingen, new Object[] { command.Meting });
                break;

            case NetCommand.CommandType.CHAT:
                ChatMessage chat = new ChatMessage(command.DisplayName, command.ChatMessage, command.IsDoctor);
                Chat.Add(chat);
                window.panelClientChat.Invoke(window.panelClientChat.passChatMessage, new Object[] { chat });
                break;
            }
        }
Esempio n. 22
0
        public bool OnCommand(NetCommand command)
        {
            if (false == CheckReliableCommand(command))
            {
                m_refServerMonitor.DisconnectSession(command.SessionID);
                return(false);
            }

            switch (command.CommandID)
            {
            case LocalCMD.ACCEPTED:
                return(OnAccepted(command));

            case LocalCMD.DISCONNECTED:
                return(OnDisconnected(command));

            case CMD.CHECK_CMD_VERSION_REQ:
                return(OnCheckCommandVersionReq(command));

            case CMD.START_SERVER_REQ:
                return(OnStartServerReq(command));

            case CMD.TERMINATE_SERVER_REQ:
                return(OnTerminateServerReq(command));

            case CMD.SET_REVIVABLE_ATT_REQ:
                return(OnSetRevivableAttReq(command));

            case CMD.GET_SERVERLIST_REQ:
                return(OnGetServerListReq(command));

            case CMD.GET_SERVERINFO_REQ:
                return(OnGetServerInfoReq(command));

            case CMD.START_ALL_SERVER_REQ:
                return(OnStartAllServerReq(command));

            case CMD.TERMINATE_ALL_SERVER_REQ:
                return(OnTerminatetAllServerReq(command));
            }
            return(true);
        }
Esempio n. 23
0
        //Пингование
        void AsyncStartPing()
        {
            Thread t = new Thread(() =>
            {
                try
                {
                    while (true)
                    {
                        TcpClient tcpClient        = new TcpClient(serverIp, serverPort);
                        NetStreamReaderWriter nsrw = new NetStreamReaderWriter(tcpClient.GetStream());
                        nsrw.ReadTimeout           = 2000;
                        NetCommand pingCmd         = new NetCommand()
                        {
                            Ip         = myIp.ToString(), //Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(),
                            Port       = ListenerPort,
                            sender     = name,            //пока что безымянный
                            cmd        = "!ping",
                            parameters = ""
                        };
                        nsrw.WriteCmd(pingCmd);
                        NetCommand ansPing = nsrw.ReadCmd();
                        if (ansPing.cmd != "!pong")
                        {
                            MessageBox.Show("Client. В ответ на пинг пришла хрень");
                        }
                        tcpClient.Close();
                        Thread.Sleep(1000);    //задержка
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Client. Сервер не отвечает на пинг");
                    connected = false;
                    lock (lbPeople)
                    {
                        lbPeople.Invoke(UpdateConnectedD);
                    }
                }
            });

            t.Start();
        }
        /// <summary>
        /// Отослать команду
        /// </summary>
        /// <param name="cmd">команда</param>
        /// <param name="param">параметры</param>
        /// <returns>ответ</returns>
        private NetCommand SendCommand(string cmd, string param, string ip, int port)
        {
            NetCommand retn = null;

            try
            {
                TcpClient tcpclient = new TcpClient(ip, port);
                NetStreamReaderWriter Stream = new NetStreamReaderWriter(tcpclient.GetStream());
                //UiWriteLog("Посылаем команду '" + cmd + " " + param + "' на " + ip + ":" + port.ToString());
                Stream.WriteCmd(CreateCommand(cmd, param));
                retn = Stream.ReadCmd();
                //UiWriteLog("Получили ответ '" + retn.cmd + " " + retn.parameters + "' от " + retn.Ip + ":" + retn.Port);
            }
            catch (Exception ex)
            {
                Debug.Write(" > Ошибка в SendCommand: " + ex.Message);
            }

            return retn;
        }
Esempio n. 25
0
        private void OnClientUpdatePicture(NetCommand command)
        {
            command.Response = new NetResponse(true);
            ParameterString uname = command.Parameters["un"]
                                    as ParameterString;

            if (uname == null)
            {
                return;
            }

            FormMsgScreen form = _Manager[uname.Value];

            if (form == null)
            {
                return;
            }

            form.InvokeRefreshImage();
        }
Esempio n. 26
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (rtfMessage.Text == string.Empty)
            {
                return;
            }

            var command = new NetCommand(CommandNames.SEND_MESSAGE);

            command.Parameters.Add(new ParameterString("un", TargetUser));
            command.Parameters.Add(new ParameterString("msg", rtfMessage.Rtf));

            _SessionManager.AddCommand(command);

            _MessageManager.AppendMessage(rtfMessage.Rtf, MessageType.SendedByMe);
            rtfMessage.Text = string.Empty;
            rtfMessage.Focus();

            _StateManager.Reset();
        }
Esempio n. 27
0
        private void Receive(string data)
        {
            string  message = Protocol.Decompress(data);
            JObject obj     = JObject.Parse(message);

            if (obj?["netCommandId"].ToString() == "serverModelSync")
            {
            }

            NetCommand netCommand = NetCommandFactory.DeserializeJson(obj, obj?["netCommandId"]?.ToString());

            if (netCommand != null)
            {
                FFB.Instance.HandleNetCommand(netCommand);
            }
            else
            {
                FFB.Instance.AddReport(RawString.Create($"<b>* * * Missing DTO for NetCommand {obj?["netCommandId"]} * * *</b>"));
            }
        }
        public bool OnCommand(NetCommand command)
        {
            switch (command.CommandID)
            {
            case LocalCMD.CONNECTED:
                return(OnConnected(command));

            case LocalCMD.DISCONNECTED:
                return(OnDisconnected(command));

            case CMD.CHECK_CMD_VERSION_RES:
                return(OnCheckCommandVersionRes(command));

            case CMD.MONITORING_LOG:
                return(OnMonitoringLog(command));

            case CMD.GET_SERVERINFO_RES:
                return(OnGetServerInfoRes(command));
            }
            return(true);
        }
Esempio n. 29
0
 private void btnLogin_Click(object sender, EventArgs e)
 {
     if (txtUsername.Text == string.Empty)
     {
         MessageBox.Show("Please enter your username");
         txtUsername.Focus();
     }
     else
     {
         if (client1.SocketStatus != SocketStatus.Connected)
         {
             client1.Connect();
         }
         else
         {
             NetCommand command = new NetCommand(CommandNames.LOGIN);
             command.Parameters.Add(new ParameterString("un", txtUsername.Text));
             client1.Commands.Add(command);
         }
     }
 }
Esempio n. 30
0
    private void parseModel(string rawData)
    {
        char[]   separator = " ".ToCharArray();
        string[] data      = rawData.Split(separator, 3);

        if (data.Length < 3)
        {
            //Debug.Log("NaC: Server Said " + rawData);
            return;
        }

        NetCommand c = new NetCommand();

        c.command = data[0];
        c.param   = data[1];
        c.data    = data[2];

        //Debug.Log("New Command : c:" + c.command + ".p:" + c.param + ".d:" + c.data);

        commandInterpreter.postOrder(c);
    }
Esempio n. 31
0
        private void Process(NetCommand message)
        {
            if (message is ServerNotAvailableCommand)
            {
                ServerNotAvailableInner((message as ServerNotAvailableCommand).Server);
            }

            else if (message is AddDistributorFromDistributorCommand)
            {
                AddDistributor(message as AddDistributorFromDistributorCommand);
            }

            else if (message is RestoreCommand)
            {
                RestoreServerCommand(message as RestoreCommand);
            }
            else
            {
                Logger.Logger.Instance.ErrorFormat("Not supported command type = {0}", message.GetType());
            }
        }
			public override void DataReceived ( NetCommand command, NetIncomingMessage msg )
			{
			}
Esempio n. 33
0
			/// <summary>
			/// Called when data arrived.
			/// It could snapshot or notification.
			/// </summary>
			/// <param name="command"></param>
			/// <param name="msg"></param>
			public override void DataReceived ( NetCommand command, NetIncomingMessage msg )
			{
				if (command==NetCommand.Snapshot) {

					//Log.Message("ping:{0} - offset:{1}", msg.SenderConnection.AverageRoundtripTime, msg.SenderConnection.RemoteTimeOffset);

					var index		=	msg.ReadUInt32();
					var prevFrame	=	msg.ReadUInt32();
					var ackCmdID	=	msg.ReadUInt32();
					var serverTicks	=	msg.ReadInt64();
					var size		=	msg.ReadInt32();

					lastSnapshotFrame	=	index;
					var snapshot		=	queue.Decompress( prevFrame, msg.ReadBytes(size) );
					
					if (snapshot!=null) {

						FeedSnapshot( snapshot, ackCmdID, index, serverTicks, index );
						queue.Push( new Snapshot(new TimeSpan(0), index, snapshot) );

					} else {
						lastSnapshotFrame = 0;
					}
				}

				if (command==NetCommand.Notification) {
					gameClient.FeedNotification( msg.ReadString() );
				}
			}
Esempio n. 34
0
			public abstract void DataReceived ( NetCommand command, NetIncomingMessage msg );