/// <summary> /// 监听方法 /// </summary> private void ListenHandler() { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 2425); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); byte[] buffer = null; while (IsListening) { System.Threading.Thread.Sleep(20); try { buffer = UdpClient.Receive(ref epGroup); } catch (Exception) { } if (buffer == null || buffer.Length < 1) { continue; } var msg = System.Text.Encoding.Default.GetString(buffer); var ip = epGroup.Address.ToString(); Thread listendthread = new Thread(listendThread); ListenedPara para = new ListenedPara(); para.Ip = ip; para.Msg = msg; listendthread.Start(para); } }
public void listendThread(object a) { string[] msgtou = null; string feiqtou = null; string msgid = null; string username = null; string hostname = null; string msgtype = null; int bodystart = 0; string msgbody = null; ListenedPara para = a as ListenedPara; string msg = para.Msg; string ip = para.Ip; if (msg.Length > 0) { msgtou = msg.Split(':'); feiqtou = msgtou[0]; msgid = msgtou[1]; username = msgtou[2]; hostname = msgtou[3]; msgtype = msgtou[4]; bodystart = feiqtou.Length + msgid.Length + username.Length + hostname.Length + msgtype.Length + 5; msgbody = msg.Substring(bodystart); } MsgType revmsgtype = (MsgType)(Int32.Parse(msgtype)); switch (revmsgtype) { case FeiQIM.MsgType.ShakeHand: SendResponeShakeHandToSomeIP(ip, msgbody); break; case FeiQIM.MsgType.Msg: SendResponeToSomeIP(msgid, ip); if (this.LISTENED_MSG != null) { LISTENED_MSG(ip, msgbody); } break; case FeiQIM.MsgType.SrceenShake: if (this.LISTENED_SRCEENSHAKE != null) { LISTENED_SRCEENSHAKE(ip); } break; case FeiQIM.MsgType.OnLine: if (AutoResend) { Thread.Sleep(200); DataRow[] dr1 = msgdt.Select("ip='" + ip + "'"); foreach (var element in dr1) { ReSendMsgToSomeIP(element); } } if (this.LISTENED_ONLINE != null) { LISTENED_ONLINE(ip); } break; case FeiQIM.MsgType.OffLine: break; case FeiQIM.MsgType.ResponeMsg: DataRow[] dr = msgdt.Select("msgid='" + msgbody + "'"); if (dr.Length > 0) { msgdt.Rows.Remove(dr[0]); } break; case FeiQIM.MsgType.Writing: if (this.LISTENED_WRITING != null) { LISTENED_WRITING(ip); } break; default: break; } }