Websocket不断断开连接(红蜘蛛)

时间:2019-08-06 10:06:31

标签: swift websocket starscream

我正在尝试订阅本地网络中Mac上托管的Websocket。但连接后几乎立即断开连接。我可以发送消息,并且可以在Mac上看到它正在接收消息(至少是命令),但是它立即断开连接。

它应该像这样工作: 我连接 我发送一个json格式的字符串:{"+":["v.altitude"]}(以订阅高度信息) Websocket定期回复{"v.altitude":71.323}

我在我的Mac上使用websocoat在本地尝试过,它看起来像这样:[Image](https://ibb.co/JqjFSs7

Xcode控制台输出以下内容:

  

正在连接。
  已连接。
  DISCONNECTED可选(“操作无法完成(Starscream.WSError错误1。)”)。

import UIKit
import Starscream

class ViewController: UIViewController, WebSocketDelegate, WebSocketPongDelegate {

    func websocketDidReceivePong(socket: WebSocketClient, data: Data?) {
        print("PONG")
    }

    var websocket: WebSocket = WebSocket(url: URL(string: "ws://192.168.178.23:8085/datalink")!)
    let jsonObject: [String: Any] = ["run":["f.light"]]//["+":["v.altitude", "v.lightValue", "v.gearValue"]]
    let dic: NSDictionary = ["run" : ["f.light"]]
    var components = URLComponents()

    override func viewDidLoad() {
        components.scheme = "ws"
        components.host = "192.168.178.23"
        components.path = "/datalink"
        components.port = 8085
        let url = components.url
        super.viewDidLoad()
        print(url!)
        websocket = WebSocket(url: url!)
        websocket.delegate = self
        print("Connecting")
        websocket.connect()
    }

    func websocketDidConnect(socket: WebSocketClient) {
        print("CONNECTED")

        let messageString = "{\"run\":[\"f.light\"]}"

        websocket.write(string: messageString)
    }

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

    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
        print("MESSAGE: STRING")
    }

    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        print("MESSAGE: DATA")
    }
}

2 个答案:

答案 0 :(得分:1)

对于Starscream 4,解决方案是

socket = WebSocket(request: request, certPinner: FoundationSecurity(allowSelfSigned: true))

答案 1 :(得分:0)

好吧,我知道了。 Starscream始终尝试验证SSL证书(我的电脑未提供),因此连接失败。 我禁用了这种行为: websocket.disableSSLCertValidation = true