Websocket keeps disconnecting (Starscream)

风流意气都作罢 提交于 2019-12-25 17:17:49

问题


I'm trying to subscribe to a Websocket hosted on a Mac in my local network. but it disconnects almost immediately after connecting. I can send messages and I can see on my Mac it is receiving them (at least commands) but then it disconnects immediately.

It is supposed to work like this: I connect I send a json formatted string : {"+":["v.altitude"]} (to subscribe to the altitude) The Websocket responds regularly with {"v.altitude":71.323}

I tried it locally on my Mac with websocoat and it looks like this: [Image] (https://ibb.co/JqjFSs7)

The Xcode console outputs this:

Connecting.
CONNECTED.
DISCONNECTED Optional("The operation couldn’t be completed (Starscream.WSError error 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")
    }
}

回答1:


Ok I figured it out. Starscream was always trying to verify the SSL Certificate (Which my pc doesn't provide) so the connection failed. I disabled this behaviour like this: websocket.disableSSLCertValidation = true



来源:https://stackoverflow.com/questions/57373637/websocket-keeps-disconnecting-starscream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!