gpt4 book ai didi

swift - Network.framework:nw_read_request_get_maximum_datagram_count

转载 作者:行者123 更新时间:2023-11-30 10:52:58 25 4
gpt4 key购买 nike

我正在尝试让 UDP 服务器在 Network.framework 中运行。但是,每当我设法连接客户端和服务器时,一段时间后我会收到错误nw_read_request_get_maximum_datagram_count

我尝试过使用 Timer 和 DispatchQueue 进行循环,但最终服务器或客户端因上述错误而崩溃。

客户端

import Foundation
import Network

class ExampleClient {
lazy var connection: NWConnection = {
let connection = NWConnection(
to: .service(
name: "Emma’s MacBook Pro",
type: "_test._udp",
domain: "local",
interface: nil
),
using: .udp
)

connection.stateUpdateHandler = { (newState) in
switch newState {
case .ready:
self.loopForever()
case .failed(let error):
print("client failed with error: \(error)")
default:
break
}
}

return connection

}()

func run() {
connection.start(queue: DispatchQueue(label: "client"))

}

func loopForever() {
while true {
connection.send(content: "hello".data(using: .utf8), completion: .contentProcessed({ (error) in
if let error = error {
print("error while sending hello: \(error)")
}

self.connection.receiveMessage { (data, context, isComplete, error) in
return

}

}))

}

}

}

let client = ExampleClient()
client.run()

RunLoop.main.run()

服务器

import Foundation
import Network

class ExampleServer {
var connections = [NWConnection]()
lazy var listener: NWListener = {
let listener = try! NWListener(using: .udp)

listener.service = NWListener.Service(type: "_test._udp")
listener.serviceRegistrationUpdateHandler = { (serviceChange) in
switch serviceChange {
case .add(let endpoint):
switch endpoint {
case let .service(name, _, _, _):
print("listening as name \(name)")
default:
break
}
default:
break
}

}
listener.newConnectionHandler = { (newConnection) in
newConnection.start(queue: DispatchQueue(label: "new client"))
self.connections.append(newConnection)

}

return listener

}()

func run() {
self.listener.start(queue: DispatchQueue(label: "server"))

while true {
for connection in self.connections {
connection.receiveMessage { (message, context, isComplete, error) in
connection.send(content: "world".data(using: .utf8), completion: .contentProcessed({ (error) in
if let error = error {
print("error while sending data: \(error)")

}

}))

}

}

}

}

}

let server = ExampleServer()
server.run()

RunLoop.main.run()

我希望保持服务器和客户端之间的持续连接,直到客户端或服务器手动断开连接。

最佳答案

在接收器中,不要将接收处理程序放入发送的完成处理程序中。

在服务器中,不要尝试将无限数量的接收处理程序排队。每个连接一次一个就足够了。

关于swift - Network.framework:nw_read_request_get_maximum_datagram_count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com