Swift Socket.io the event sent right after connect

2019-09-05 16:08发布

问题:

So I am trying to send (emit) an event right after the connection.

I am building a chat app, and the only issue I have is that when the user disconnected and connect to the server again, other clients are not informed the reconnected client is back (I think it is because my userlist data at the server end is not updated when the reconnected client is back) So I'm trying to send an event right after the connection to update the userlist data at the server end. But seems like the event is not executed for some reason. Any help would be great!

func establishConnection() {
    socket.connect()

    if UsersViewController.nickname != nil {
        socket.emit("connectWithNewId", UsersViewController.nickname)
    }
}

I have check already that the event can be send from the other place of the code. It just seems not working right after the connection.

回答1:

You should emit the event when the connection is established, try something like this:

func establishConnection() {
    socket.on("connect") { data, ack in
        if UsersViewController.nickname != nil {
            socket.emit("connectWithNewId", UsersViewController.nickname)
        }
    }

    socket.connect()
}