日期:2014-05-18 浏览次数:21064 次
try { byte[] data = new byte[1024]; string msg; //构建UDP服务器 // Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName()); //设置服务IP,设置UDP端口号 //定义网络类型,数据连接类型和网络协议UDP string welcome = "L" + UserHelper.loginUser.id.ToString(); data = Encoding.UTF8.GetBytes(welcome); sokClient.SendTo(data, data.Length, SocketFlags.None, ipep); byte[] arrMsg2 = System.Text.Encoding.UTF8.GetBytes("H"+UserHelper.loginUser.id.ToString()); sokClient.SendTo(arrMsg2, arrMsg2.Length, SocketFlags.None,ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制 //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100); int recv = sokClient.ReceiveFrom(data, ref Remote); Console.WriteLine(" from {0}: ", Remote.ToString()); Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv)); while (true) { //server.SendTo(Encoding.UTF8.GetBytes("ok"), Remote); data = new byte[1024]; recv = sokClient.ReceiveFrom(data, ref Remote); msg = Encoding.UTF8.GetString(data, 0, recv); if (msg.Length > 0) { string headCommand = msg.Substring(0, 1); switch (headCommand) { case "N": string content = msg.Substring(1); //MsgNewsForm mnf = new MsgNewsForm(content); // MsgPresentationManage.GetInstance().AddMsgNewsForm(mnf); MessageBox.Show(msg); break; case "M": string sendUserId = msg.Substring(1); OAUsers user = userBLL.GetModel(int.Parse(sendUserId)); UserHelper.SendUserName = user.userName; timerSend.Enabled = true; timerSend.Start(); notifyIcon1.Icon = PPSoft.Properties.Resources._1; break; case "H": string heartUserId = msg.Substring(1); Console.WriteLine(heartUserId + "发来的心跳包"); break; default: break; } } Console.WriteLine(msg); } } catch (Exception ex) { }