private void Listen() { while (!listener_stop) { string message = Receiver.GetMessage(); if (message != "") { AbstractCommand command = CommandDecoder.Decode(message); if (command != null) { if (command is StartCommand) { Game.Start(); } else if (command is PauseCommand) { Game.Pause(); } else if (command is StopCommand) { Game.Stop(); } else if (command is PushCommand) { (Game as ServerGameEngine).Push((command as PushCommand).Number); } // Других случаев быть не может, т.к. нераспознанная команда равна null } Console.WriteLine(message); // в целях отладки } } }
/// <summary> /// Получает очередное сообщение от сервера и, если идентифицирует команду, обращается к GameController, который инициирует соответствующее событие /// </summary> private void Listen() { while (!listener_stop) { string message = Receiver.GetMessage(); if (message != null && message != "") { AbstractCommand command = CommandDecoder.Decode(message); if (command != null) { if (command is StartCommand) { Game.Start(); } else if (command is PauseCommand) { Game.Pause(); } else if (command is StopCommand) { Game.Stop(); } else if (command is RiseNewCommand) { (Game as ClientGameController).RiseNew((command as RiseNewCommand).Places); } else if (command is PushCommand) { (Game as ClientGameController).Push((command as PushCommand).Number); } else if (command is LoseCommand) { (Game as ClientGameController).Lose((command as LoseCommand).Result); } else if (command is ChangeHpCommand) { (Game as ClientGameController).ChangeHp((command as ChangeHpCommand).Hp); } else if (command is RiseProgressCommand) { (Game as ClientGameController).RiseProgress( (command as RiseProgressCommand).Place, (command as RiseProgressCommand).Stage); } } } } }
void ReciveMsg() { while (ReceivingData) { EndPoint point = new IPEndPoint(IPAddress.Any, 0); //用来保存发送方的ip和端口号 byte[] buffer = new byte[1024]; int length = server.ReceiveFrom(buffer, ref point); //接收数据报 var cmd = new CommandDecoder(); FrontCommand fc; bool result = cmd.Decode(buffer, out fc); if (fc.Header.MainCommand == (ushort)GroupCarNetworkCommands.MainCommands.UDPConnect && fc.Header.SubCommand == (ushort)GroupCarNetworkCommands.UDPSubCommands.Response_AskHeartBeat) { InitTcpNetwork(point.ToString().Split(':') [0]); } } }
//服务器接收 void SocketReceive() { //进入接收循环 while (true) { //对data清零 recvData = new byte[1024]; //获取客户端,获取客户端数据,用引用给客户端赋值 recvLen = socket.ReceiveFrom(recvData, ref clientEnd); outStr += "message from: " + clientEnd.ToString() + "\n"; recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen); var cmd = new CommandDecoder(); FrontCommand fc; bool result = cmd.Decode(buffer, out fc); Debug.Log("message from: " + clientEnd.ToString() + "\n" + recvStr); //打印客户端信息 //输出接收到的数据 outStr += recvStr + clientEnd.ToString() + "\n"; //将接收到的数据经过处理再发送出去 sendStr = "From Server reply: " + recvStr; SocketSend(recvData); SocketSend(sendStr); } }