//与逻辑层后台的交互 private void OnServerCall(object sender, ServerEventArgs e) { if (e.type == ServerMessageType.LOGIN) { state = "CONNECTED"; ID_Public = e.message; } else if (e.type == ServerMessageType.ERROR) { this.Dispatcher.Invoke(new Action(delegate { Message.Show(MessageFunction.Autoclose, "Error!", e.message + "\nLogin.cs/69"); })); } else { this.Dispatcher.Invoke(new Action(delegate { Message.Show(MessageFunction.Autoclose, "Error!", "你收到了你不该收到的消息!\n程序猿一定写错了什么!" + "\nLogin.cs/73"); })); } }
public void ServerResponse()//响应服务器的命令 { //定义一个byte数组,用于接收从服务器端发来的数据 //每次所能接受的数据包的最大长度为1024个字节 byte[] Response = new byte[1024]; string Msg; int Len; try { if (Stream.CanRead == false) { return; } while (true) { Len = Stream.Read(Response, 0, Response.Length); if (Len < 1) { Thread.Sleep(200); continue; } Msg = Encoding.GetEncoding("gb2312").GetString(Response, 0, Len); Msg.Trim(); //下面为处理各种命令 if (Msg == "lol") { ServerEventArgs login = new ServerEventArgs(ServerMessageType.LOGIN, ID_Public); servermessage(this, login); break; } else if (Msg == "loo") { ServerEventArgs logout = new ServerEventArgs(ServerMessageType.LOGOUT, ID_Public); servermessage(this, logout); break; } else if (Msg == "n") { ServerEventArgs query = new ServerEventArgs(ServerMessageType.QUERYOFFLINE, ID_Public); servermessage(this, query); break; } else { IPAddress ip = null; if (IPAddress.TryParse(Msg, out ip)) { ServerEventArgs query = new ServerEventArgs(ServerMessageType.QUERYONLINE, Msg); servermessage(this, query); break; } else { ServerEventArgs error = new ServerEventArgs(ServerMessageType.ERROR, Msg); servermessage(this, error); break; } } } //关闭连接 tcpClient.Close(); } catch (Exception ex) { //向UI层返回一个出错的信号 ServerEventArgs error = new ServerEventArgs(ServerMessageType.ERROR, ex.Message); servermessage(this, error); } }