iossocketswebsocketswift4.2starscream

Websocket connection via starscream in ios


Currently I'm using Action Cable client to connect to the URL and subscribe to the channel. But the library seems to have some issues as its occasionally fails to subscribe to channel. Below is my current setup code for Action cable client

func setupActionCable(){

        guard let urlString = URL(string: "wss://mysocketurl.com/path") else {return}

        let headers = ["Origin":"https://mysocketurl.com"]
        self.client = ActionCableClient(url: urlString, headers:headers)

        self.client?.willConnect = {
            print("Will Connect")
        }

        self.client?.onConnected = {
            print("Connected to \(String(describing: self.client?.url))")
            print("Client = \(String(describing: self.client))")
            self.createChannel()
        }

        self.client?.onDisconnected = {(error: ConnectionError?) in
            print("Disconected with error: \(String(describing: error))")
        }

        self.client?.willReconnect = {
            print("Reconnecting to \(String(describing: self.client?.url))")
            return true
        }

        self.client?.onPing = {

            guard let channel = self.channel else {return}
            print("Ping received = \(String(describing: channel))")
        }
    }

    func createChannel(){

        let room_identifier = ["room_id" : roomID]
        self.channel = client?.create("MyChannel", identifier: room_identifier)

        self.channel?.onSubscribed = {
            print("Subscribed to \(self.ChannelIdentifier) with simulation Id = \(self.simulationID)")
        }

        self.channel?.onReceive = {(data: Any?, error: Error?) in

            print("****** channel response data = \(String(describing: data))")
            if let error = error {
                print(error.localizedDescription)
                return
            }
        }

        self.channel?.onUnsubscribed = {
            print("Unsubscribed")
        }

        self.channel?.onRejected = {
            print("Rejected")
        }
    }

Now I'm trying to migrate to starscream for resolving this issue. But I'm not really sure on how to set it up below is my start up code. func setupStarScream() {

        var request = URLRequest(url: URL(string: "wss://mysocketurl.com/path")!)
        request.httpMethod = "POST"
        request.timeoutInterval = 5
        socket = WebSocket(request: request)
        socket.delegate = self
        socket.connect()
    }

This always give me an "Invalid HTTP upgrade" error. Probably because I have not added the origin and channel detail like in the action cable. But I don't know how to go add it here. Any help is appreciated.


Solution

  • Try this

    func setupStarScream(){
            var request = URLRequest(url: URL(string: "wss://mysocketurl.com/path")!)
            request.addValue("https://mysocketurl.com", forHTTPHeaderField: "Origin")
            socket = WebSocket(request: request)
            socket?.delegate = self
            socket.connect()
        }
    

    Once connected create a channel like this

    func websocketDidConnect(socket: WebSocketClient) {
            print("websocket is connected")
            createChannel()
        }
    
    func createChannel()
        {
            let strChannel = "{ \"channel\": \"MyChannel\",\"room_id\": \"\(roomID)\" }"
            let message = ["command" : "subscribe","identifier": strChannel]
    
            do {
                let data = try JSONSerialization.data(withJSONObject: message)
                if let dataString = String(data: data, encoding: .utf8){
                    self.socket?.write(string: dataString)
                }
    
            } catch {
                print("JSON serialization failed: ", error)
            }
    
        }