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