如何在 NWConnection 中为 UDP 广播设置发送者端口

How to set the sender's port in NWConnection for UDP broadcast

我有一个小型 ruby 服务器,我想用 iOS 应用程序向它发送一条 UDP 消息。 它运行良好,但(发件人)iOS 端口每次都是一个随机端口,我希望它是一个固定端口。

这是发送消息的 iOS 代码:

guard let data = "Hello".data(using: .utf8) else { return }
let queue = DispatchQueue(label: "connection")
let params = NWParameters.udp
client = NWConnection(host: NWEndpoint.Host("255.255.255.255"), port: NWEndpoint.Port(integerLiteral: 49000), using: params)
client?.start(queue: queue)
client?.send(content: data, completion: .idempotent)

这里是 Ruby 服务器的输出,其中显示了发件人和消息:

AF_INET
51269 <----------- Port is not 49001
192.168.1.241
192.168.1.241
48656c6c6f
AF_INET
60451 <----------- Port is not 49001
192.168.1.241
192.168.1.241
48656c6c6f

我尝试添加此参数以将发送方套接字设置为固定值 49001。

params.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host("0.0.0.0"), port: 49001)

但它也不起作用。有什么想法吗?

感谢您的帮助,网络框架的文档很差。

它适用于不在模拟器上的实际 iOS 设备。