一、概述
UDP和TCP是网络通讯常用的两个传输协议,C#一般可以通过Socket来实现UDP和TCP通讯,由于.NET框架通过UdpClient、TcpListener 、TcpClient这几个类对Socket进行了封装,使其使用更加方便, 本文就通过这几个封装过的类讲解一下相关应用。
二、UDP基本应用
与TCP通信不同,UDP通信是不分服务端和客户端的,通信双方是对等的。为了描述方便,我们把通信双方称为发送方和接收方。
发送方:
首先创建一个UDP对象:
string locateIP = "127.0.0.1"; //本机IP int locatePort = 9001; //发送端口 IPAddress locateIpAddr = IPAddress.Parse(locateIP); IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort); UdpClient udpClient = new UdpClient(locatePoint);
发送数据:
string remoteIP = "127.0.0.1"; //目标机器IP int remotePort = 9002; //接收端口 IPAddress remoteIpAddr = IPAddress.Parse(remoteIP); IPEndPoint remotePoint = new IPEndPoint(remoteIpAddr, remotePort); byte[] buffer = Encoding.UTF8.GetBytes(“hello”); udpClient.Send(buffer, buffer.Length, remotePoint);
以上就完成了一个发送任务,一个较完整的发送代码如下:
public partial class FormServer : Form { private UdpClient udpClient = null; private void btnConnect_Click(object sender, EventArgs e) { string locateIP = "127.0.0.1"; int locatePort = 9001; IPAddress locateIpAddr = IPAddress.Parse(locateIP); IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort); udpClient = new UdpClient(locatePoint); this.groupWork.Enabled = true; } private void Send_Click(object sender, EventArgs e) { string text = this.txtSend.Text.Trim(); string remoteIP = "127.0.0.1"; int remotePort = 9002; byte[] buffer = Encoding.UTF8.GetBytes(text); if (udpClient != null) { IPAddress remoteIp = IPAddress.Parse(remoteIP); IPEndPoint remotePoint = new IPEndPoint(remoteIp, remotePort); udpClient.Send(buffer, buffer.Length, remotePoint); } Debug.WriteLine("Send OK"); } }
接收端:
首先创建一个UDP对象:
string locateIP = "127.0.0.1"; int locatePort = 9002; IPAddress locateIpAddr = IPAddress.Parse(locateIP); IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort); UdpClient udpClient = new UdpClient(locatePoint);
接收数据:
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"), 1); var received = udpClient.Receive(ref remotePoint); string info = Encoding.UTF8.GetString(received); string from=$” {remotePoint.Address}:{remotePoint.Port}”;
注意两点:
1、remotePoint是获得发送方的IP信息,定义时可以输入任何合法的IP和端口信息;
2、Receive方法是阻塞方法,所以需要在新的线程内运行,程序会一直等待接收数据,当接收到一包数据时程序就返回,要持续接收数据需要重复调用Receive方法。
一个较完整的接收端代码如下:
public partial class FormClent : Form { private UdpClient udpClient = null; private void btnConnect_Click(object sender, EventArgs e) { string locateIP = "127.0.0.1"; int locatePort = 9002; IPAddress locateIpAddr = IPAddress.Parse(locateIP); IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort); udpClient = new UdpClient(locatePoint); IPEndPoint remotePoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"), 1); Task.Run(() => { while (true) { if (udpClient<a>本文来源gao*daima.com搞@代#码&网6</a> != null) { var received = udpClient.Receive(ref remotePoint); string info = Encoding.UTF8.GetString(received); string from=$” {remotePoint.Address}:{remotePoint.Port}”; } } }); } }