0

我使用“Swifter”作为我的本地 HTTP 服务器。我正在为 WebSockets 使用“红蜘蛛”。

不幸的是,websocket is disconnected: Optional("The operation couldn’t be completed. (Starscream.WSError error 1.)"))当我尝试连接时。

我尝试从浏览器访问 localhost,看起来 Http Server 工作正常。

下面是我正在处理的代码:

简单服务器:

import Foundation
import Swifter

class SimpleServer{

    let server: HttpServer = HttpServer()

    public func startServer(){
        do {
            server["/hello"] = { .ok(.htmlBody("You asked for bhuvesh \($0)"))  }
            try server.start(8000)
        }
        catch{
            print("Server could not be started")
        }
    }

}

视图控制器:

import UIKit
import Starscream

class ViewController: UIViewController, WebSocketDelegate {

    @IBOutlet weak var button: UIButton!

    var socket: WebSocketClient!
    var simpleServer = SimpleServer()

    override func viewDidLoad() {
        super.viewDidLoad()
        simpleServer.startServer()

        socket = WebSocket(url: URL(string: "ws://localhost:8000")!)
        socket.delegate = self
        socket.connect()
    }

    func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
        print("websocket is disconnected: \(error?.localizedDescription))")
    }

    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
        print("got some text: \(text)")
    }

    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        print("got some data: \(data.count)")
    }

    func websocketDidConnect(socket: WebSocketClient) {
        print("websocket is connected")
    }
}

4

1 回答 1

0

我有完全相同的问题。你试过用你的 Mac 和 websocat 连接它吗?如果它在那里失败了两个,那么它可能与您的服务器有关,如果不是,您可能遇到与我完全相同的问题。

于 2019-08-06T10:21:58.650 回答