简体   繁体   中英

what is actually the default behavior of socket.io?

I'm using socket.io on the client as well as on the server side. It is a great library, but I must say that the default behavior is not described in the docs, which make using the library so confusing. At least I didn't find any references for the default behavior.

Basically, I watched tutorials, where a basic chat app was build with socket.io. In the tutorials, the server send a message automatically to all conected clients. Is this the default behavior in the server side?

I'm not sure about this. I'm developing an app where the user can (un)subscribe to specific topics and receive values from the server. Let's say I have two topics (topic1 and topic2). I opened two clients (client1 and client2) and I subscribed to topic1 from client1. I noticed that I received the value1 of topic1 in client1 but client2 received nothing.

const io = require('socket.io')(3000); // create server
  io.on('connection', socket => {
      console.log("client is connected over sockets");
    socket.on('subscribe', () => {socket.emit('send-msg', "send to client");})
  });

In this case above, will the server send to all clients or to only one client. Can you clarify this to me and tell me what is the default behavior of socket.io please


PS: Another thing I noticed about socket.io is that there is many ways to do the same thing and it is not documented well. Like for example, I'm instantiating a client with socketIOClient function: const socket = socketIOClient("my_host"); But I ve seen many tutorials that uses the openSocket function or even directly the io function (here for some reason the author added this in the html <script defer src="http://localhost:3000/socket.io/socket.io.js"></script> )

All these function do the same thing, right?

You're looking at the difference between namespace.emit and socket.emit . A socket is one specific connection, and emitting an event on it sends it only to that one connection. A namespace on the other hand is a group of several sockets, and emitting an event on it emits it to every socket in the group. The entire io server is one namespace by default, so io.emit(...) sends a message to all connected clients. You can group your sockets into arbitrary namespaces and rooms to make it easy to send messages to selected groups.

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