OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 Swift iOS 中监听来自服务器的网络数据? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 21:46
标题: ios - 如何在 Swift iOS 中监听来自服务器的网络数据?

我正在创建一个应用程序来测试 iOS 和 Swift 中的网络框架。但是如何创建代码以便我可以从服务器接收数据,就像一个监听器?我正在使用 UDP 连接。

我已经尝试过使用“receive”或“receiveMessage”方法,但我一直不知道如何收听。它只是在应用程序连接到服务器时接收数据,而不是在服务器发送到客户端应用程序时接收数据。

//This is the receiveMessage approach from the client in Swift:
class UDPClient {

var connection: NWConnection
var queue: DispatchQueue
weak var controller: ViewController?

init() {
    queue = DispatchQueue(label: "UDP Client Queue")

    connection = NWConnection(host: "<secret>", port: 8888, using: .udp)

    connection.stateUpdateHandler = { [weak self] (newState) in
        switch newState {
        case .ready:
            print("ready to send")
            self?.sendInitialMessage()
        case .failed(let error):
            print("client faild with error: \(error)")
        default:
            break
        }
    }

    connection.start(queue: queue)
}

func sendInitialMessage() {
    let helloMessage = "hello from iPhone".data(using: .utf8)
    connection.send(content: helloMessage, completion: .contentProcessed({ (error) in
        if let error = error {
            print("Send error: \(error)")
        }
    }))

    connection.receiveMessage { (content, context, isComplete, error) in
        if content != nil {
            print("Got message")
            let text = String(data: content!, encoding: .utf8)
            print(text!)
        }
    }
}

func send(content: Data) {
    connection.send(content: content, completion: .contentProcessed({ (error) in
        if let error = error {
            print("Send error: \(error)")
        }
    }))
}
}

//This is the server PHP code:
$socket = socket_create(AF_INET, SOCK_DGRAM, 0);

socket_bind($socket, "<secret>", 0000);

while (true) {
    socket_recvfrom($socket, $buffer, 100, 0, $rip, $rport);

    echo "Received ". $buffer. " from ". $rip . $rport . "\n";

    socket_sendto($socket, "hi", 2, 0, $rip, $rport);
}

我希望应用程序在服务器通过监听套接字数据发送“hi”消息时打印“hi”。



Best Answer-推荐答案


尝试实现其他 stateUpdateHandler 枚举案例,请参阅此处的文档 https://developer.apple.com/documentation/network/nwconnection/state

如果您想拥有一个可靠的 UDP 网络库,而不仅仅是学习基础知识,您可以使用 CocoaAsyncSocket 而无需重新发明轮子: https://github.com/robbiehanson/CocoaAsyncSocket

关于ios - 如何在 Swift iOS 中监听来自服务器的网络数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160429/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4