我想使用 MAMP 和 Starscream 库https://github.com/daltoniam/Starscream将 iPhone 连接到在我的 Macbook 上运行的 Web 服务器 使用 Cocoapods 安装并使用以下 URL 设置 Web 服务器:localhost:8888 但我是因为代码不起作用而头疼...我遵循了所有在线指南,官方文档等,但没有一个对我有帮助...每当我运行代码时,控制台都会显示以下消息:websocket已断开连接:HTTP 升级无效
所以也许是我的服务器坏了?我尝试改用 ws://echo.websocket.org/ 并且成功了!!!所以我想......因为它最终向我展示了:websocket 已连接但同时它没有!事实上,socket.isConnected 方法给了我错误...之后,如果我调用 socket.disconnect() 它也不起作用,也不会显示任何消息。
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
let socket = WebSocket(url: URL(string:"ws://echo.websocket.org/")!)//websocket is connected
/*
let socket = WebSocket(url: URL(string: "ws://localhost:8888/")!) //websocket is disconnected: Invalid HTTP upgrade
*/
override func viewDidLoad() {
super.viewDidLoad()
socket.delegate = self
socket.connect()
if socket.isConnected {
print("hi1") //it doesn't get printed
}
if !socket.isConnected {
print("hi2") //it gets printed
}
}
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if let e = error as? WSError {
print("websocket is disconnected: \(e.message)")
} else if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("Received data: \(data.count)")
}
}