服務端代碼
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8090));
EndPoint clientPoint= new IPEndPoint(IPAddress.Any, 0); // 聲明一個空的端口對象香缺,當接受到數(shù)據(jù)的時候手销,會將數(shù)據(jù)發(fā)送方的地址賦值到該對象中
byte[] reciveData = new byte[1024];
int dataLength = server.ReceiveFrom(reciveData, ref clientPoint); //接收到連接,會將連接方的地址寫入clientPoint
string reciveMessage = Encoding.UTF8.GetString(reciveData, 0, dataLength);
Console.WriteLine(reciveMessage);
server.Close();
Console.ReadKey();
}
客戶端代碼
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string userMessage = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(userMessage);
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 8090);
clientSocket.SendTo(data, serverPoint);
Console.ReadKey();
}