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

How to work with UDP sockets in iOS, swift?(如何在 iOS 中快速使用 UDP 套接字?)

本文介绍了如何在 iOS 中快速使用 UDP 套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到本地 esp8266 UDP 服务器.SwiftSocket 没有文档.CocoaAsyncSocket 不起作用.如何连接并发送数据到 udp 服务器?我该怎么办?

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 should do?

我编写了示例 UDP python 服务器并尝试通过 SwiftSocket 和 CocoaAsyncSocket 连接到它们.我没有从应用程序中获得反馈.服务器不接收连接.例如 - 最多的尝试之一:

I wrote sample UDP python server and tried connect to them via SwiftSocket and CocoaAsyncSocket. I'm don't get feedback from app. Server don't receive connections. For example- one of the most attempts:

    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 服务器(这不是最佳版本,但有效):

This solution work for me! Thanks @Paulw11
Swift 4, XCode 10.1, iOS 12.0
Simple connect to the public UDP server (This is NOT optimal version but works):

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
")
                    self.sendUDP(messageToUDP)
                    self.receiveUDP()
                case .setup:
                    print("State: Setup
")
                case .cancelled:
                    print("State: Cancelled
")
                case .preparing:
                    print("State: Preparing
")
                default:
                    print("ERROR! State not defined!
")
            }
        }

        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: 
 (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: 
 (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")
                }
            }
        }
    }
}

这篇关于如何在 iOS 中快速使用 UDP 套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 iOS 中快速使用 UDP 套接字?

基础教程推荐