ios - 我如何在 Swift iOS 中监听来自服务器的网络数据?

标签 ios swift

我正在创建一个应用程序来测试 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”。

最佳答案

尝试实现其他 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/

相关文章:

ios - 如何从 iOS 应用程序调用 WhatsApp 电话?

objective-c - 拖动 UIImages 到选中区域

swift - 在 UIImageView 周围填充。 swift 3

ios - 来自 CloudKit 的推送通知未正确同步

ios - Swift UI 中的动画文本

ios - 如何让我的形象隐藏在我的标签后面?

swift 字典 : join key and value into string

objective-c - shouldAutorotateToInterfaceOrientation 被多次调用 - 这正常吗?

iOS:如何从文档目录中删除所有具有特定扩展名的现有文件?

ios - AutoLayout:垂直到水平没有明确的尺寸?