C# 有UDPServer嘛
时间: 2023-11-29 22:47:28 浏览: 31
是的,C#中有UDPServer。以下是一个简单的UDP服务器端的示例代码:
```csharp
using System;
using System.Net;using System.Net.Sockets;
using System.Text;
class UDPServer
{
static void Main(string[] args)
{
// 设置服务器IP和端口号
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8888;
// 创建UDP服务器
UdpClient udpServer = new UdpClient(port);
// 打印服务器已启动
Console.WriteLine("UDP服务器已启动...");
// 循环接收客户端发送的消息
while (true)
{
// 接收客户端消息
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] receiveBytes = udpServer.Receive(ref remoteIpEndPoint);
string receiveString = Encoding.UTF8.GetString(receiveBytes);
// 打印接收到的消息
Console.WriteLine("接收到客户端消息:" + receiveString);
// 发送响应消息给客户端
string responseString = "已收到消息:" + receiveString; byte[] responseBytes = Encoding.UTF8.GetBytes(responseString);
udpServer.Send(responseBytes, responseBytes.Length, remoteIpEndPoint);
}
}
}
```
以上代码创建了一个UDP服务器,监听本地IP地址127.0.0.1和端口号8888,循环接收客户端发送的消息,并发送响应消息给客户端。
以下是一个简单的UDP客户端的示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UDPClient
{
static void Main(string[] args)
{
// 设置服务器IP和端口号
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 8888;
// 创建UDP客户端
UdpClient udpClient = new UdpClient();
// 发送消息给服务器
string sendString = "Hello, UDP Server!";
byte[] sendBytes = Encoding.UTF8.GetBytes(sendString);
udpClient.Send(sendBytes, sendBytes.Length, new IPEndPoint(ip, port));
// 接收服务器响应消息
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
string receiveString = Encoding.UTF8.GetString(receiveBytes);
// 打印服务器响应消息
Console.WriteLine("接收到服务器响应消息:" + receiveString);
// 关闭UDP客户端
udpClient.Close();
}
}
```
以上代码创建了一个UDP客户端,向本地IP地址127.0.0.1和端口号8888的服务器发送消息,并接收服务器的响应消息。