/// <summary> /// 登录. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { serverPoint = new IPEndPoint(IPAddress.Parse(this.txtServerIP.Text), Convert.ToInt32(this.nudServerPort.Value)); messageSender.IPEndPoint = serverPoint; SystemMessage message = new SystemMessage() { Header = new MessageHeader() { CommandID = MessageHeader.QM_Login_Req, SequenceNo = sequence++, }, Body = new LoginRequest() { UserName = this.txtUserName.Text, Password = "******" }, }; ShowMessage("发送 :" + message.ToString()); // 发送登录消息. messageSender.SendMessage(message); // 接收反馈. SystemMessage resultMessage = messageReceiver.ReceiveMessage(); ShowMessage("接收 :" + resultMessage.ToString()); userToken = ((LoginRespond)(resultMessage.Body)).UserToken; if (userToken != Guid.Empty) { // 已登录. HadLogin(); // 心跳包后台处理. if (bgwKeepAlive.IsBusy != true) { // Start the asynchronous operation. bgwKeepAlive.RunWorkerAsync(); } if (bgwReceive.IsBusy != true) { // Start the asynchronous operation. bgwReceive.RunWorkerAsync(); } } }
/// <summary> /// 线程主方法 /// </summary> private void Run() { // 消息接收器. UdpClientMessageReceiver receiver = new UdpClientMessageReceiver(); receiver.UdpClient = _server; receiver.IPEndPoint = _remotePoint; // 消息发送器. UdpClientMessageSender sender = new UdpClientMessageSender(); sender.UdpClient = _server; while (true) { // 接收消息. SystemMessage message = receiver.ReceiveMessage(); Console.WriteLine("接收-({0}:{1})>{2}", receiver.IPEndPoint.Address, receiver.IPEndPoint.Port, message.ToString()); SystemMessage resultMessage = messageProcess.DoMessageProcess(receiver.IPEndPoint, message); // 设置接收方. sender.IPEndPoint = receiver.IPEndPoint; // 发送. sender.SendMessage(resultMessage); Console.WriteLine("答复-({0}:{1})>{2}", sender.IPEndPoint.Address, sender.IPEndPoint.Port, resultMessage.ToString()); } }