gpt4 book ai didi

ios - Swift Network.framework WebSocket 握手 nil 返回

转载 作者:行者123 更新时间:2023-12-01 16:14:06 40 4
gpt4 key购买 nike

我正在尝试使用新的 Network.framework 连接到 WebSocket,但面临来自服务器的零握手响应。

(是的,我知道红蜘蛛存在,但它不支持代理/移动用户在网络接口(interface)之间切换)

我的测试代码:

func beginTest() {

let connection = NWConnection(host: "echo.websocket.org", port: 443, using: .tls)

connection.stateUpdateHandler = { state in
print("State:", state)
switch state {
case .ready:
self.connectionReady(connection)
default:
break
}
}
connection.start(queue: .main)
}

func connectionReady(_ connection: NWConnection) {

let raw = """
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.org
Origin: https://echo.websocket.org
Sec-WebSocket-Key: s04nPqA7M6pQ3Lu2jRJLSQ==
Sec-WebSocket-Version: 13
"""

let rawData = raw.appending("\n\n\n").replacingOccurrences(of: "\n", with: "\r\n").data(using: .utf8)

connection.send(content: rawData!, completion: .idempotent)

connection.receiveMessage(completion: {data, context, bool, error in
if let data = data {
print("Received:", String(data: data, encoding: .utf8))
}

print("Error:", error)

let hello = "Hello".data(using: .utf8)
connection.send(content: hello, completion: .idempotent)
})
}

这是零响应和连接断开,而不是从服务器获取升级握手响应,下面带有控制台日志:
State: preparing
State: ready
Received: nil
Error: nil
2018-10-08 11:38:57.314885+0800 SwiftNetworkTest[86448:3026660] [] nw_socket_handle_socket_event [C1.1:2] Socket SO_ERROR [54: Connection reset by peer]

谁能指导我如何使用 Apple 新的 Network.framework?将不胜感激!

更新1
  • 我的错,我现在可以使用 .ascii 看到握手响应编码而不是 .utf8 .
  • 但我的连接仍然断开 Connection reset by peer .升级到 WebSocket 后如何保持连接?
  • 最佳答案

    您应该遵循 Websocket 指南如何格式化 Websocket 发送的消息。

    我认为这是一个很好的资源。我自己用过。

    https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

    关于ios - Swift Network.framework WebSocket 握手 nil 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52695147/

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