C# UDP通讯实例
2024-09-07 09:03:42
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, , "127.0.0.1", );
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();
string message = ei.GetString(ReceviceBuff, , ReceviceBuff.Length);
if (message.Length > )
{
// 处理接收逻辑 } }
3、UdpService代码
public class UdpService
{
#region 内部变量 string devIP = "127.0.0.1";
int devPort = ;
UdpClient mySocket;
string meIP = "127.0.0.1";
int mePort = ;
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 = ; 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[];
byte[] sendwritbuf = new byte[]; while (isRunning)
{
try
{
if (mySocket == null || mySocket.Available < )
{
Thread.Sleep();
continue;
}
//接收UDP数据报,引用参数RemotePoint获得源地址
byte[] buf = mySocket.Receive(ref RemotePoint);
if (devIP == null || devIP.Length < )
{
devIP = RemotePoint.Address.ToString();
devPort = RemotePoint.Port;
}
if (EvtGetValues != null)
{
EvtGetValues(buf);
}
}
catch (Exception)
{
}
}
}
#endregion
}
最新文章
- div中设置滚动条的问题
- 51nod p1201 整数划分
- hibernate-DetachedCriteria实现关联表条件复查
- C# 非UI线程对控件的控制
- 桐桐的贸易--WA
- (17)odoo方法和修饰器
- leetcode:Intersection of Two Linked Lists(两个链表的交叉点)
- C#反编译工具 ILSPY-x64可动态调试-君临汉化版
- Universal-Image-Loader源码解解析---display过程 + 获取bitmap过程
- i春秋官网4.0上线啦 文末有福利
- DeeplabV3+ 训练自己的遥感数据
- 关系网络数据可视化:2. Python数据预处理
- java.lang.NumberFormatException: multiple points错误问题
- 转 利用 Console 来学习、调试JavaScript
- SSL编程(2).NET最简单的客户端
- <;摘录>;开源软件架构-ZeroMQ
- linux小白
- UISearchDisplayController
- Python学习---匿名函数和闭包的学习
- 通过SectionIndexer实现微信通讯录