About the use of socket. IO

During this period of time, I learned socket. IO and used it to write small projects. Here, I summarize its basic use methods and some key points. Socket. IO is an open source framework for real-time communication based on Node.js and WebSocket protocols, including client-side JavaScript and server-side Node.js.

The service side

The backend framework is koA2, where socket. IO binds itself to koA processes, the most important of which are Connection and disconnect. They are system events defined by the framework itself, which means they are natural and do not need to be customized. There are other system events, but they are rarely used.

const koa = require('koa')
const app = new koa()
const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)

// Listen for connect events
io.on('connection', socket => {
  socket.emit('open');// Notify the client that it is connected
  console.log('connected');
  
  // Listen for the disconnect event
  socket.on('disconnect', () = > {console.log('disconnect')}}); server.listen(3001);
Copy the code

The client

The Web side simply passes in the URL address. The open event monitored here is user-defined, and the corresponding server sends the Open event.

import io from 'socket.io-client';

// Establish a Websocket connection
const socket = io('http://127.0.0.1:3001');

// Received a connection confirmation from the server
socket.on('open', () => {
    showTip('socket io is open ! ');
    init();
});
Copy the code

Emit and on

Emit and ON are the two most important apis, corresponding to send and listen events, respectively.

  • Socket. emit(eventName[,…args]) : emits an event
  • Socket. on(eventName, callback) : listens for an emit event

We can very freely define and send an event emit on the server side and then listen on the client side and vice versa.

The content can be in a variety of formats, ranging from basic data types such as Number, String, Boolean, Object, Array, and even functions. Using callback functions allows for a more portable interaction.

/*** server **/
socket.on('message',data =>{
  console.log(data)
});

socket.emit('send'.'hello everybody');

/*** * client **/
socket.emit('message', {id:'1'.txt:'hello'});

socket.on('send',data =>{
  console.log(data);
});

// The callback function
/*** server **/
socket.on('sayit', (word, callback)=> {
  callback('say ' + word);
});

/*** * client **/
socket.emit('sayit'.'wow', data => { 
  console.log(data); // say wow
});
 
Copy the code

Broadcast radio

By default, broadcast broadcasts to all socket connections, excluding the sender itself. If the sender intends to receive a message, it must send the message to itself.

/*** server **/
io.on('connection', socket => {
 const data= {
   txt:'new user login'.time:new Date()}// Broadcast connections to all sockets
 socket.broadcast.emit('userin',data);
 // Send a copy to yourself
 socket.emit('userin',data);
});
Copy the code

Namespace namespace

If you want to isolate scopes, or partition business modules, namespace is an effective way to do this. A namespace is like creating new channels, and you can isolate different connections, events, and middleware on a socket. IO service.

The default connection also has a namespace, that is /;

The first way to use namespaces is to add subdomain names directly after links. This is using the same Sokcet service process.

/*** * client **/
import io from 'socket.io-client';

// The default namespace
const socket = io('http://127.0.0.1:3001');
// mypath
const socket = io('http://127.0.0.1:3001/mypath', { forceNew: true });

/*** server **/
// The default namespace
io.on('connection', socket => {
});
// mypath
io.of('/mypath').on('connection', socket => {
});
Copy the code

The second way to use the namespace is with the path parameter, which is essentially a new socket service.

/*** * client **/
const socket = io('http://localhost', {
  path: '/mypath'
});

/*** server **/
// Restart the socket service
const io = require('socket.io') ({path: '/mypath'
});
Copy the code

Middleware middleware

Socket. IO’s middleware is very similar to Kao2’s, which means we can adapt koA2’s middleware for socket. IO with very little change.

const mypath = io.of('/mypath').on('connection', socket => {
    socket.on('message', data => {
    });
});

/ / middleware
const auth = (socket, next) = > {
  const data = socket.request;
  if(! verify(data)){throw new Error('not verify');
  }
  next();
}
// mypath This namespace registers middleware
mypath.use(auth);
Copy the code

rooms

Each socket connection has a unique identifier, socket.id, which is used to distinguish connections. In addition, socket.id itself is also the symbol of a room. Generally speaking, each socket connection has its own room. So we can send messages to the room, and if you join the room, you can receive broadcast messages from the room. Of course, you can customize room to allow socket connections to join or leave. And if the socket disconnects, which is disconnect, it is automatically removed from the room.

This is the basis for individual chat and group chat. Take a look at the CORRESPONDING API.

  • Socket. join(rooms[, callback]) : Joins the room
  • Socket.leave (room[, callback]) : leaves the room
  • Socket. to(room) : sends messages to the room
// Customize room
io.on('connection', socket =>{    
  socket.join('some room')); // Join the room
  socket.leave('some room'); // Leave the room
}); 

// Send messages to all clients in the room
io.to('some room').emit('some event'); 

// Default room (one room for each id)
socket.on('say to someone', (id, msg) => {    
    socket.broadcast.to(id).emit('my message', msg); 
}); 
Copy the code

conclusion

Believe that with the above introduction of the basic knowledge, coupled with the corresponding official website documents, to develop chat rooms or other real-time communication projects, is a piece of cake

The socket. IO website has a very detailed explanation of the API and use cases.