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

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:

主站蜘蛛池模板: 高安市| 周口市| 德安县| 新和县| 漾濞| 马龙县| 康乐县| 永川市| 三明市| 东乌| 白朗县| 驻马店市| 建始县| 呼玛县| 昭通市| 馆陶县| 吉安市| 江阴市| 汉寿县| 那曲县| 海兴县| 湘西| 东丽区| 光泽县| 台山市| 南部县| 嘉峪关市| 马尔康县| 天峻县| 洪湖市| 南城县| 保定市| 沐川县| 彝良县| 义马市| 万山特区| 安庆市| 澎湖县| 景宁| 登封市| 赣州市|