1

我想使用 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)")
    }

}
4

1 回答 1

-4

所以我终于明白了这个问题:Apache默认不支持Web Sockets......这就是我收到错误消息的原因。然后代码与“ws://echo.websocket.org/”一起工作。您只需将所有 socket.x 函数放在 viewDidLoad() 之外即可使它们工作,例如断开连接按钮中的 socket.disconnect、sendButton 中的 socket.write 等。

例如:

let socket = WebSocket(url: URL(string: "ws://echo.websocket.org/")!) 

override func viewDidLoad() {
    super.viewDidLoad()

    socket.delegate = self
    socket.connect()

}

@IBAction func sendButtonPressed(_ sender: UIButton) {
    socket.write(string: textField.text!)
}
于 2019-09-26T15:32:13.363 回答