Search code examples
swiftsocket.ioratchet

Swift SocketIO Client not holding connection


I am attempting to connect to a socket. I can see the connection connect and disconnect in my terminal when I launch or close my app but anytime I try to emit I get an error

SocketIOClient: Handling event: error with data: ["Tried emitting connect when not connected"]

If I am showing as connected in the terminal why is my app not recognizing the connection?

I am using Ratchet as a php socket server.

class SocketIOManager: NSObject {
    var socket: SocketIOClient?
    override init() {
        super.init()
        self.socket = SocketIOClient(socketURL: URL(string: "http://166.62.121.191:8495")!, config: [.log(true), .reconnects(true), .reconnectWait(10), .forcePolling(true), .forceWebsockets(true)])
    }

    static let instance = SocketIOManager()

    func establishConnection() {
        socket?.onAny { (event: SocketAnyEvent) -> Void in
            print("Got event: \(event.event), with items: \(event.items)")
        }
        socket?.on("connect") { (data, ack) in
            print(data)
        }
        socket?.connect()
    }

    func closeConnection() {
        socket?.disconnect()
    }
}

Solution

  • This might have to do with your backend. The one I'm working on requires a client to send 'keep alive' message every 10 seconds, or else it will terminate the connection.

    What I had to do is create NSTimer and emit a simple message that looks like this:

        func keepAlive(){
           let socketData = [Key.type: "serviceAlive"] as [String : Any]
           socket.emit("message", socketData)
        }
    

    socket.io uses a ping/pong scheme to regularly send packets between client and server. If that regular set of transmissions is interrupted, then either client or server will know that the other end is no longer connected. This behavior is built into socket.io already.