How to work with UDP sockets in iOS, swift?

前端 未结 2 1867
-上瘾入骨i
-上瘾入骨i 2020-12-30 13:57

I\'m trying connect to local esp8266 UDP server. SwiftSocket haven\'t documentation. CocoaAsyncSocket doesn\'t work. How to connect and send data to udp server? What i shoul

2条回答
  •  粉色の甜心
    2020-12-30 14:36

    You need to wait until your connection is in the ready state before you try and send or receive any data. You will also need to hold a strong reference to your connection in a property to prevent it from being released as soon as the function exits.

    var connection: NWConnection?
    
    func someFunc() {
    
        self.connection = NWConnection(host: "255.255.255.255", port: 9093, using: .udp)
    
        self.connection?.stateUpdateHandler = { (newState) in
            switch (newState) {
            case .ready:
                print("ready")
                self.send()
                self.receive()
            case .setup:
                print("setup")
            case .cancelled:
                print("cancelled")
            case .preparing:
                print("Preparing")
            default:
                print("waiting or failed")
    
            }
        }
        self.connection?.start(queue: .global())
    
    }
    
    func send() {
        self.connection?.send(content: "Test message".data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            print(NWError)
        })))
    }
    
    func receive() {
        self.connection?.receiveMessage { (data, context, isComplete, error) in
            print("Got it")
            print(data)
        }
    }
    

提交回复
热议问题