简体   繁体   中英

Socket emit fails

  socket.on('sign_in', function(idA, idB) {
var idA = idA; //global vars
var idB = idB; //ignore this var
if (!clients[idA]) {
  clients[idA] = socket.id;
}
console.log(idA + ' has connected');
io.to(clients[idA]).emit('sign_in', idA + ' has connected'); });

io.emit('sign_in', "user is signed in");

I am trying to emit the message,"'idA' has connected" to my android client. The problem is that the emitting to a specific client only works once. After it is called once the server stops sending the line "'idA' has connected". I have to reset my server in order to get it to work again, but the problem lingers. The basic io emit function consistently works which leads me to think its a problem with the specific client emit. I have tried adding the option 'forceNew' to my socket connection but it does not change anything (I am using nkzawa socket-client).

my client code:

IO.Options options = new IO.Options();
        options.forceNew = true;
        socket = IO.socket(HOST, options);

and then using a new thread:

new Thread(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "attempting to connect socket");
            socket.connect();
            idA = "user1"
            idB = "nicknameOfUser1"
            socket.emit("sign_in", idA, idB);
        }
    }).start();

receiving the emit:

socket.on("sign_in", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                    String message = (String) args[0];
                    System.out.println(message);
            }
        });

Again, the message "'idA' has connected" will only print out the first time. But the message "user has signed in" is called consistently each time.

Turns out that my emit was written incorrectly.

io.to(clients[idA]).emit('sign_in', idA + ' has connected');

should be

clients[idA].emit('sign_in', idA + ' has connected');

also be sure to assign

clients[idA] = socket;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM