基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)
使用Udp协议通讯需要具备以下几个条件:
(1).建立一个套接字(Socket)
(2).绑定服务器端IP地址及端口号--服务器端
(3).通过SendTo()方法向指定主机发送消息 (需提供主机IP地址及端口)
(4).通过ReciveFrom()方法接收指定主机发送的消息 (需提供主机IP地址及端口)
下面用代码实现简单的服务器---客户端通信
服务器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _023_socket编程_UDP协议_服务器端 {
class Program
private static Socket udpServer;
static void Main(string[] args) {
//1,创建socket
udpServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
//2,绑定ip跟端口号
udpServer.Bind( new IPEndPoint( IPAddress.Parse("192.168.1.101"),7788 ) );
//3,接收数据
new Thread(ReceiveMessage){ IsBackground = true}.Start();
Console.WriteLine("服务器启动...");
Console.ReadKey();
static void ReceiveMessage()
while (true)
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//这个方法会把数据的来源(ip:port)放到第二个参数上
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "收到了数据:" + message);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace _002_socket编程_udp协议_客户端 {
class Program {
static void Main(string[] args) {
//创建socket
Socket udpClient = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
while (true)
//发送数据
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 7788);
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpClient.SendTo(data, serverPoint);
udpClient.Close();
Console.ReadKey();
执行过程:
(1)启动服务器
(2)启动客户端,并向服务器发送数据