gpt4 book ai didi

c# - 从同一个套接字发送和接收数据的简单 UDP 示例

转载 作者:IT王子 更新时间:2023-10-29 03:59:09 25 4
gpt4 key购买 nike

出于某种原因,我很难从同一个套接字发送和接收数据。无论如何,这是我的客户端代码:

var client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening (testing localy)
client.Connect(ep);

// send data
client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);

// then receive data
var receivedData = client.Receive(ref ep); // Exception: An existing connection was forcibly closed by the remote host

基本上我想创建一个协议(protocol),我发送一个 udp 数据包然后我期待一个响应。就像每个请求都有一个响应的 HTTP 协议(protocol)一样。 如果服务器位于不同的计算机上,则此代码有效。虽然可能存在服务器和客户端位于同一台计算机上的情况。

这是服务器:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
var groupEP = new IPEndPoint(IPAddress.Any, 11000); // listen on any port
var data = udpServer.Receive(ref groupEP);
udpServer.Send(new byte[] { 1 }, 1); // if data is received reply letting the client know that we got his data
}

编辑

我不能使用 tcp 的原因是因为有时客户端在 NAT(路由器)后面,并且 UDP 打洞比 TCP 更简单。


解决方案:

感谢 markmnl 的回答,这是我的代码:

服务器:

UdpClient udpServer = new UdpClient(11000);

while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP); // listen on port 11000
Console.Write("receive data from " + remoteEP.ToString());
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // reply back
}

客户端代码:

var client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening
client.Connect(ep);

// send data
client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);

// then receive data
var receivedData = client.Receive(ref ep);

Console.Write("receive data from " + ep.ToString());

Console.Read();

最佳答案

(我假设您知道使用 UDP(用户数据报协议(protocol))不能保证交付、检查重复项和拥塞控制,只会回答您的问题。

在你的服务器中这一行:

var data = udpServer.Receive(ref groupEP);

groupEP 从您所拥有的重新分配给您收到东西的地址。

这一行:

udpServer.Send(new byte[] { 1 }, 1); 

将不起作用,因为您没有指定将数据发送给谁。 (它适用于您的客户端,因为您调用了连接,这意味着发送将始终发送到您连接的端点,当然我们不希望在服务器上出现这种情况,因为我们可能有很多客户端)。我会:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}

此外,如果您在同一台机器上有服务器和客户端,您应该将它们放在不同的端口上。

关于c# - 从同一个套接字发送和接收数据的简单 UDP 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com