UDP(User Datagram Protocol) 用户数据报协议,与 TCP 不同, UDP 并不提供对 IP 协议的可靠机制、流控制以及错误恢复功能等。由于 UDP 比较简单, UDP 头包含很少的字节,比 TCP 负载消耗少。
UDP 适用于不需要 TCP 可靠机制的情形,比如,当高层协议或应用程序提供错误和流控制功能的时候。 UDP 是传输层协议,服务于很多知名应用层协议,包括网络文件系统(NFS)、简单网络管理协议(SNMP)、域名系统(DNS)以及简单文件传输系统(TFTP)。
网上关于Udp通讯的程序很多,但是笔者发现很多程序都有问题,所以将自己在工作中做的Udp通讯代码关键的地方列出来,供大家学习参考。
1.udp通讯业分为服务器端和客户端,客户端发送数据,服务器端接收数据,首先是客户端代码,下面是一个客户端的Udp类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SerialInterface
{
public class Udp
{
private UdpClient updCliet;
private IPEndPoint ipEndPoint;
/// <summary>
/// 初始化
/// </summary>
public void Inital()
{
try
{
updCliet = new UdpClient();
ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
//客户端连接
updCliet.Connect(ipEndPoint);
}
catch (Exception error)
{
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="dgram"></param>
public void SendToUdp(byte [] dgram ,int len)
{
try
{
updCliet.Send(dgram, dgram.Length);
}
catch (Exception error)
{
}
}
/// <summary>
/// 关闭Udp客户端
/// </summary>
public void CloseUdp()
{
updCliet.Close();
}
}
}
2.服务器端需要通过线程去接收处理数据:
try
{
updCliet = new UdpClient();
ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
//客户端绑定
updCliet.Client.Bind(ipEndPoint);
thread = new Thread(new ThreadStart(ReceiveData));
thread.IsBackground = true;
thread.Start();
}
catch (Exception error)
{
}
public void ReceiveData()
{
while (true)
{
try
{
byte[] bytes = updCliet.Receive(ref ipEndPoint);
//接收并转换的字符串
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
catch (Exception error)
{
}
}
}