官术网_书友最值得收藏!

Broadcasting a message

The Ping-Pong app that we built shows all the events, regardless of their source. If someone else pings, it shows in our list. If we ping, it shows on our list. We do not want to do this. We only want the application to show if someone else pings. Showing our own pings isn't necessarily a bad feature to have. What makes it bad is that we send the ping to the server and the server sends it back to us. We can (and will) make it more efficient by only sending the ping to everyone else. How?

Broadcast! This seems to be a misnomer. If you are broadcasting something, you think it goes out to everyone. This is very close to what Socket.IO does. Broadcast will send it out to everyone but you. If there are four clients connected, Socket.IO will send it to the other three. Let's wire it all up.

We will only have to change the server side, as we will use the same event names. We are just changing who they will go to. Inside app.js in the io.sockets.on('connection'), we will change both the emits, as shown in the following code:

socket.on('join', function(data){
    socket.broadcast.emit('userJoined', data);
    socket.username = data.username;
  });

  socket.on('ping', function(data, done){
    socket.broadcast.emit('ping', {username: socket.username});
    done('ack');
  });

All we had to do was change io.sockets to socket.broadcast. We are still using the emit method in the same way.

It makes sense why we have to use socket instead of io.sockets. Remember that io is tied to the whole Socket.IO server. It is what is returned from require('socket.io').listen(4000). Then, we are getting all the sockets off io. This would be every connected client, including us. Finally, emit is called, which sends a message to each one.

The Socket.IO connection object is referenced from the callback when a socket is connected. The socket is in the context of one specific socket connection. socket.emit will send our message object back to the connected socket. socket.broadcast.emit will then send our message object back to all others, except for the connected socket that initiated the broadcast.

What will happen now is that any event you are sending to the server will not get an event back. The join event will return userJoined with our username. Now, we only get it when someone else joins. The same is true for our pings. Only other pings will show in our list. We will still get acknowledgements on the pings we send, so our ping counter will still work. Go ahead and load http://localhost:8000 in a couple of browser tabs and check out what happens.

The following screenshot is how our Socket.IO application should function:

主站蜘蛛池模板: 枝江市| 苍南县| 泊头市| 库尔勒市| 监利县| 青神县| 阿鲁科尔沁旗| 新源县| 中阳县| 乌兰察布市| 沅陵县| 揭东县| 米脂县| 三江| 扶余县| 安化县| 新巴尔虎左旗| 句容市| 凤城市| 义乌市| 靖州| 治县。| 河南省| 亳州市| 英超| 工布江达县| 琼结县| 临武县| 永昌县| 星子县| 彭阳县| 西贡区| 攀枝花市| 永和县| 灵宝市| 康乐县| 湖州市| 巨野县| 六枝特区| 松阳县| 吉安县|