public static void Send(string msg, bool isSend = true, UdpServiceReciveDelege _udpServiceRecive = null) { if (udp == null) { string localIP = "127.0.0.1"; string localPort = "8001"; string sendIP = "127.0.0.1"; string sendPort = "8000"; if (!isSend) { string tmp = localPort; localPort = sendPort; sendPort = tmp; } udpServiceRecive = _udpServiceRecive; udp = new UdpClient(new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPort))); sendHost = new IPEndPoint(IPAddress.Parse(sendIP), Convert.ToInt32(sendPort)); Thread t = new Thread(() => { try { IPEndPoint from = null; while (true) { try { byte[] b = udp.Receive(ref from); string str = Encoding.UTF8.GetString(b, 0, b.Length); if (udpServiceRecive != null) { udpServiceRecive(str); } //Console.WriteLine(str); } catch (Exception e) { //Console.WriteLine(e.Message); } } } catch { //LogService.Mess("前台关闭"); } finally { udp.Close(); } }); t.IsBackground = true; t.Start(); } if (isSend) { byte[] _b = Encoding.UTF8.GetBytes(msg); udp.Send(_b, _b.Length, sendHost); } }
public UdpService(string localIP, string localPort, string sendIP, string sendPort, UdpServiceReciveDelege _udpServiceRecive) { udp = new UdpClient(new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPort))); sendHost = new IPEndPoint(IPAddress.Parse(sendIP), Convert.ToInt32(sendPort)); udpServiceRecive = _udpServiceRecive; ThreadPool.QueueUserWorkItem(new WaitCallback((m) => { IPEndPoint from = null; while (true) { try { byte[] b = udp.Receive(ref from); string str = Encoding.UTF8.GetString(b, 0, b.Length); if (udpServiceRecive != null) { udpServiceRecive(str); } //Console.WriteLine(str); } catch (Exception e) { Console.WriteLine(e.Message); } } } )); }
public UdpService(string localIP, string localPort, string sendIP, string sendPort, UdpServiceReciveDelege _udpServiceRecive) { udp = new UdpClient(new IPEndPoint(IPAddress.Parse(localIP), Convert.ToInt32(localPort))); if (!(sendIP == null || sendPort == null || sendIP == "" || sendPort == "")) { sendHost = new IPEndPoint(IPAddress.Parse(sendIP), Convert.ToInt32(sendPort)); } udpServiceRecive = _udpServiceRecive; ThreadPool.QueueUserWorkItem(new WaitCallback((m) => { IPEndPoint from = null; try { while (true) { try { byte[] b = udp.Receive(ref from); string str = Encoding.UTF8.GetString(b, 0, b.Length); if (udpServiceRecive != null) udpServiceRecive(str); //Console.WriteLine(str); } catch (Exception e) { Console.WriteLine(e.Message); } } } catch (Exception e) { udp.Close(); } } )); }