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

Posted

技术标签:

【中文标题】如何在 Swift iOS 中监听来自服务器的网络数据?【英文标题】:How do i listen for network data from the server in Swift iOS? 【发布时间】:2019-01-12 14:18:25 【问题描述】:

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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于如何在 Swift iOS 中监听来自服务器的网络数据?的主要内容,如果未能解决你的问题,请参考以下文章

iOS Swift 从网络流中播放音频(aac)

如何在 swift/iOS 中更新谷歌地图标记位置

如何在 ios 中知道设备与哪个网络主机连接

在nodejs中使用socket.io和net socket

iOS8/Swift 奇怪的空行为与来自 REST 服务的响应

监听蓝牙外设按钮事件 iOS Swift