我想使用MAMP和Starscream Library 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)")
}
}
答案 0 :(得分:0)
所以我终于明白了这个问题:默认情况下,Apache不支持Web套接字...这就是为什么我收到错误消息的原因。然后,代码将与“ ws://echo.websocket.org/”一起使用。您只需要将所有socket.x函数放在viewDidLoad()外部即可使其正常工作,例如,在Disconnect Button中插入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!)
}