gpt4 book ai didi

c# - udp 在 .net 中的工作原理

转载 作者:行者123 更新时间:2023-11-30 16:22:46 24 4
gpt4 key购买 nike

有人告诉我 UDP 是无连接的,这意味着您无法确定包裹是否会到达目的地。

为什么这样做:

var dataToSend = new byte[]{1};
UdpClient client = new UdpClient();
client.Send(dataToSend,1,"192.168.0.45", 1234);

变量 LocalEndpoint 初始化:

enter image description here

如果我错了请纠正我。我相信变量 LocalEndPoint 是由路由器初始化的。我之所以相信这是因为每次服务器 (192.168.0.45) 接收数据然后回复时,我都看到数据正在通过回复中的端口 62446 发送。

所以我的问题是如果我使用的是 udp 协议(protocol),为什么我会收到路由器的响应?如果我从路由器收到响应,那么这不是 UDP,或者我对 udp 的理解有误。我不认为端口号是随机选择的。如果我已经将路由器配置为在端口 62446 上将端口转发到其他计算机,那么我的程序将无法运行。


这是客户端代码:

string ipOfServer = "192.168.0.45";
int portServerIsListeningOn = 1234;

// send data to server
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sending_end_point = new IPEndPoint(IPAddress.Parse(ipOfServer), portServerIsListeningOn);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);

// after I send data localendpoint gets initialized! and the server always respond through that port!

// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];

// now wait for server to send data back
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer); // <----- keeps waiting in here :(

这是服务器代码:

// wait for client to send data
UdpClient listener = new UdpClient(11000);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
byte[] receive_byte_array = listener.Receive(ref groupEP);
listener.Connect(groupEP);

// reply
byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
listener.Send(dataToSend, dataToSend.Length);

最佳答案

Bind 为您提供 LocalEndPoint 属性中包含的信息,而不是路由器:

此节选自MSDN :

The LocalEndPoint property gets an EndPoint that contains the local IP address and port number to which your Socket is bound. You must cast this EndPoint to an IPEndPoint before retrieving any information. You can then call the IPEndPoint.Address method to retrieve the local IPAddress, and the IPEndPoint.Port method to retrieve the local port number.

The LocalEndPoint property is usually set after you make a call to the Bind method. If you allow the system to assign your socket's local IP address and port number, the LocalEndPoint property will be set after the first I/O operation. For connection-oriented protocols, the first I/O operation would be a call to the Connect or Accept method. For connectionless protocols, the first I/O operation would be any of the send or receive calls.

但是您的理解是正确的,UDP 是一种即刻即弃的数据发送方式。

关于c# - udp 在 .net 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12189986/

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