美文网首页
Swift使用udp之Hello,world

Swift使用udp之Hello,world

作者: 左卫门_6e62 | 来源:发表于2020-03-23 16:21 被阅读0次

    主要用到了Network模块下的NWConnection,下面的代码向localhost的20131端口发送"Hello,world!"

    let msg="Hello,world!"
    let hostUDP: NWEndpoint.Host = "127.0.0.1"
    let portUDP: NWEndpoint.Port = 20131
        
    var connection=NWConnection(host: hostUDP, port: portUDP, using: .udp)
        
    connection.stateUpdateHandler = { (newState) in
        print("This is stateUpdateHandler:")
        switch (newState) {
            case .ready:
                print("State: Ready\n")
                sendUDP(msg)
            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")
        }
    }
        
    connection.start(queue: .global())
        
    func sendUDP(_ msg:String){
        let contentToSend=msg.data(using: String.Encoding.utf8)
        connection.send(content: contentToSend, completion: NWConnection.SendCompletion.contentProcessed({(NWError) in
            if NWError==nil{
                print("Data was sent to UDP")
            }else{
                print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
            }
        }))
    }
    sendUDP(msg)
    

    相关文章

      网友评论

          本文标题:Swift使用udp之Hello,world

          本文链接:https://www.haomeiwen.com/subject/oovwyhtx.html