簡體   English   中英

如何在 iOS 中快速使用 UDP 套接字?

[英]How to work with UDP sockets in iOS, swift?

我正在嘗試連接到本地 esp8266 UDP 服務器。 SwiftSocket 沒有文檔。 CocoaAsyncSocket 不起作用。 如何連接和發送數據到udp服務器? 我該做什么?

我編寫了示例 UDP python 服務器並嘗試通過 SwiftSocket 和 CocoaAsyncSocket 連接到它們。 我沒有得到應用程序的反饋。 服務器不接收連接。 例如 - 最多的嘗試之一:

    var connection = NWConnection(host: "255.255.255.255", port: 9093, using: .udp)

    connection.stateUpdateHandler = { (newState) in
        switch (newState) {
        case .ready:
            print("ready")
        case .setup:
            print("setup")
        case .cancelled:
            print("cancelled")
        case .preparing:
            print("Preparing")
        default:
            print("waiting or failed")
            break
        }
    }
    connection.start(queue: .global())
    connection.send(content: "Xyu".data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
        print(NWError)
    })))
    connection.receiveMessage { (data, context, isComplete, error) in
        print("Got it")
        print(data)
    }

無法連接到服務器

這個解決方案對我有用! 謝謝@Paulw11
Swift 4、XCode 10.1、iOS 12.0
簡單連接到公共 UDP 服務器(這不是最佳版本但有效):

import UIKit
import Network

class ViewController: UIViewController {

    var connection: NWConnection?
    var hostUDP: NWEndpoint.Host = "iperf.volia.net"
    var portUDP: NWEndpoint.Port = 5201

    override func viewDidLoad() {
        super.viewDidLoad()

        // Hack to wait until everything is set up
        var x = 0
        while(x<1000000000) {
            x+=1
        }
        connectToUDP(hostUDP,portUDP)
    }

    func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
        // Transmited message:
        let messageToUDP = "Test message"

        self.connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)

        self.connection?.stateUpdateHandler = { (newState) in
            print("This is stateUpdateHandler:")
            switch (newState) {
                case .ready:
                    print("State: Ready\n")
                    self.sendUDP(messageToUDP)
                    self.receiveUDP()
                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")
            }
        }

        self.connection?.start(queue: .global())
    }

    func sendUDP(_ content: Data) {
        self.connection?.send(content: content, 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!)")
            }
        })))
    }

    func sendUDP(_ content: String) {
        let contentToSendUDP = content.data(using: String.Encoding.utf8)
        self.connection?.send(content: contentToSendUDP, 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!)")
            }
        })))
    }

    func receiveUDP() {
        self.connection?.receiveMessage { (data, context, isComplete, error) in
            if (isComplete) {
                print("Receive is complete")
                if (data != nil) {
                    let backToString = String(decoding: data!, as: UTF8.self)
                    print("Received message: \(backToString)")
                } else {
                    print("Data == nil")
                }
            }
        }
    }
}

在嘗試發送或接收任何數據之前,您需要等到連接處於ready狀態。 您還需要在屬性中保存對您的連接的強引用,以防止它在函數退出時立即被釋放。

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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM