客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace UDP协议_客户端
{
class Program
{
static void Main(string[] args)
{
//创建Socket
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
while (true)
{
//发送数据
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.3.41"), 7788);
udpClient.SendTo(data, serverPoint);
}
udpClient.Close();
Console.ReadKey();
}
}
}
服务器端
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 UDP协议_服务器端
{
class Program
{
private static Socket udpServer;
static void Main(string[] args)
{
//创建Socket
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//绑定ip跟端口
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.3.41"), 7788));
//接收数据
//开启线程
new Thread(ReceiveMessage) { IsBackground=true}.Start();//IsBackground后台线程
// udpServer.Close();
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);//ref表示 udpServer.ReceiveFrom可以对 remoteEndPoint做修改
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port.ToString() + "收到了数据:" + message);
}
}
}
}