本文介绍了一个基于Winfrom的UDP通信例程:
服务器:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udp_server
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("UDP服务器");
//AddressFamily.InterNetwork 表示IPV4的意思
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //SocketType.Dgram 数据包格式---UDP SocketType.Stream 流格式---TCP
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 42, 27 }); //win+R ---cmd --ipconfig--看你的IPv4的IP,因为是字节用逗号分割
IPEndPoint iPEndPoint = new IPEndPoint(ipAddress, 7788); //ip + 端口号 //服务器IP +端口
//UDP 不用连接 也不用监听 直接接收、发送数据包即可
udpServer.Bind(iPEndPoint); //服务器绑定自己是这个ip+端口
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0); //any 表示任意一个UDP客户端都可以连上本服务器 端口也没限制
EndPoint ep = (EndPoint)ipep; //强转一下格式不然传不了参数
byte[] data = new byte[1024];
int recive_lenght = udpServer.ReceiveFrom(data,ref ep);
Console.WriteLine("接收到的数据:"+ Encoding.UTF8.GetString(data,0,recive_lenght));
udpServer.Close(); //不用的话就要关闭
}
}
}
客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace udp_client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("客户端");
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //SocketType.Dgram 数据包格式---UDP SocketType.Stream 流格式---TCP
byte[] data = Encoding.UTF8.GetBytes("你好,客户端上线了");
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 42, 27 }); //win+R ---cmd --ipconfig--看你的IPv4的IP,因为是字节用逗号分割
IPEndPoint iPEndPoint = new IPEndPoint(ipAddress, 7788); //ip + 端口号 //服务器IP +端口
//对于UDP来说 严格意义上是没有客户端和服务器之分的 发送用sendto 接收用reciveform
udpClient.SendTo(data, iPEndPoint);
udpClient.Close();
}
}
}
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/73e8db7552154c730830fd3d6fd8c105.png)
![](https://i-blog.csdnimg.cn/blog_migrate/7ade335eceb040646ad5f3e070e99343.png)
总结一下TCP和UDP的区别:
TCP和UDP的区别
TCP协议和UDP协议连接过程的区别
1.基于连接与无连接:
2.对系统资源的要求 (TCP较多,UDP少) ;
3.UDP程序结构较简单:
4.流模式与数据报模式 ;
5.TCP保证数据正确性,UDP可能丢包,TCP保证数据顺序,UDP不保证。
注:一般下载都用TCP,保证数据完整传输。