C# UDP通讯实例
Posted lzsin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# UDP通讯实例相关的知识,希望对你有一定的参考价值。
1、发送方代码
void SendMsg(string toip, int port ) { try { string message="发送内容"; UdpClient udpclient = new UdpClient(); IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(ip), port); byte[] data = Encoding.Default.GetBytes(message); udpclient.Send(data, data.Length, ipendpoint); udpclient.Close(); } catch (Exception ex) { MessageBox.Show("UDP发送数据" + ex.ToString()); } }
2、接收方代码
public UdpService udp; a>实例化、初始化接收事件 udp = new UdpService(fromip, 60000, "127.0.0.1", 60000); udp.EvtGetValues+=new UdpService.GetRecevice(udp_EvtGetValues); b>启动UDP udp.TurnOn(); c>停止UDP udp.TurnOff(); d>接收事件处理 void udp_EvtGetValues(byte[] ReceviceBuff) { //string message = Encoding.UTF8.GetString(ReceviceBuff, 0, ReceviceBuff.Length); //可接收中文内容 Encoding ei=Encoding.GetEncoding(936); string message = ei.GetString(ReceviceBuff, 0, ReceviceBuff.Length); if (message.Length > 0) { // 处理接收逻辑 } }
3、UdpService代码
public class UdpService { #region 内部变量 string devIP = "127.0.0.1"; int devPort = 60000; UdpClient mySocket; string meIP = "127.0.0.1"; int mePort = 60000; IPEndPoint RemotePoint; bool isRunning = false; bool isOpen = false; List<Thread> listThread = new List<Thread>(); string icId = ""; string cardContent = ""; byte[] cardContentBuf; #endregion public UdpService(string ServerIP, int ServerPort, string DevIP, int DevPort) { this.meIP = ServerIP; this.mePort = ServerPort; this.devIP = DevIP; this.devPort = DevPort; } #region public void TurnOn() { try { if (isOpen) return; mySocket = new UdpClient(mePort); IPEndPoint ipLocalPoint = new IPEndPoint(IPAddress.Parse(meIP), mePort); RemotePoint = new IPEndPoint(IPAddress.Any, devPort); isRunning = true; Thread thread = new Thread(new ThreadStart(this.ReceiveHandle)); thread.IsBackground = true; thread.Start(); listThread.Add(thread); isOpen = true; } catch (Exception ex) { isOpen = false; throw new Exception(ex.Message); } } public void TurnOff() { try { isOpen = false; isRunning = false; for (int i = 0; i < listThread.Count; i++) { try { listThread[i].Abort(); } catch (Exception) { } } if (mySocket != null) { mySocket.Close(); } } catch (Exception) { } } public delegate void GetRecevice(byte[] ReceviceBuff); public event GetRecevice EvtGetValues; private void ReceiveHandle() { byte[] sendbuf = new byte[9]; byte[] sendwritbuf = new byte[200]; while (isRunning) { try { if (mySocket == null || mySocket.Available < 1) { Thread.Sleep(300); continue; } //接收UDP数据报,引用参数RemotePoint获得源地址 byte[] buf = mySocket.Receive(ref RemotePoint); if (devIP == null || devIP.Length < 1) { devIP = RemotePoint.Address.ToString(); devPort = RemotePoint.Port; } if (EvtGetValues != null) { EvtGetValues(buf); } } catch (Exception) { } } } #endregion }
以上是关于C# UDP通讯实例的主要内容,如果未能解决你的问题,请参考以下文章
如何为 XSLT 代码片段配置 CruiseControl 的 C# 版本?
如何编程使上位机(界面c#)与下位机(单片机keil c)通过TCP/UDP协议来实现通信,最好有源代码,谢谢~~