我将“ Swifter”用作本地HTTP服务器。 我正在为WebSocket使用“ Starscream”。
不幸的是,当我尝试连接时得到websocket is disconnected: Optional("The operation couldn’t be completed. (Starscream.WSError error 1.)"))
。
我尝试从浏览器访问localhost,看起来Http Server运行正常。
下面是我正在处理的代码:
SimpleServer:
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")
}
}
}
ViewController:
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")
}
}
答案 0 :(得分:0)
我有完全相同的问题。您是否尝试过用Mac和websocat连接到它? 如果它失败了,那么可能有两个问题,如果不是,那可能与您的服务器有关。