指定localEndpoint的UDP NWConnection适用于IPv4地址,但不适用于IPv6地址

时间:2019-06-12 12:11:50

标签: swift sockets udp

我正在使用SBlintsov How to work with UDP sockets in iOS, swift?提供的代码 但是,我也想指定“ requiredLocalEndpoint”。为此,以下代码适用于IPv4地址,但对于IPv6地址,连接将停在准备状态。

func connectToGroupUDP2(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
    // Set requiredLocalNWEndpoint
    let devicePort = NWEndpoint.hostPort(host: NWEndpoint.Host.ipv6(IPv6Address(cellularIp!)!), port: 54712)
    print("\(devicePort)")
    let parameters = NWParameters.udp
    print("\(parameters)")
    parameters.requiredLocalEndpoint = devicePort
    print("\(parameters)")
    connectionGroup2 = NWConnection(host: hostUDP, port: portUDP, using: parameters)
    let messageToUDP = "group2"
    connectionGroup2?.stateUpdateHandler = { (newState) in
        print("This is group2 stateUpdateHandler:")
        switch (newState) {
        case .ready:
            print("State: Ready\n")
            sendGroupUDP2(messageToUDP)
        case .setup:
            print("State: Setup\n")
        case .cancelled:
            print("State: Cancelled\n")
        case .preparing:
            print("State: Preparing\n")
        default:
            print("ERROR! State not defined!\n")
        }
    }
    connectionGroup2?.start(queue: .global())
}

Xcode控制台显示以下打印输出:

2001:b400:e401:c376:554b:48b9:9a89:a81.54712
udp, indefinite
udp, local: 2001:b400:e401:c376:554b:48b9:9a89:a81.54712, indefinite
This is group2 stateUpdateHandler:
State: Preparing

但是,该代码适用于IPv4地址,

let devicePort = NWEndpoint.hostPort(host: NWEndpoint.Host.ipv4(IPv4Address(wifiIp!)!), port: 54712)

打印输出如下

192.168.1.103:54712
udp, indefinite
udp, local: 192.168.1.103:54712, indefinite
This is group2 stateUpdateHandler:
State: Preparing

This is group2 stateUpdateHandler:
State: Ready

group2 was sent to groupServer2

如何解决此问题?

0 个答案:

没有答案