📜  socket.io (1)

📅  最后修改于: 2023-12-03 15:35:01.657000             🧑  作者: Mango

Socket.io

Socket.io is a JavaScript library for real-time web applications. It provides us with a way to keep instant two-way communication between the server and the client.

Features
  • Real-time communication
  • Event-driven architecture
  • Supports multiple transports (WebSocket, Polling, etc.)
  • Supports broadcasting to multiple clients
  • Automatic reconnection
  • Room and namespace support
Installation

To install Socket.io, use the following command:

npm install socket.io
Usage

Server-side:

const io = require('socket.io')(server);

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

Client-side:

const socket = io();

$('form').submit((e) => {
  e.preventDefault(); // prevents page reloading
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
});

socket.on('chat message', (msg) => {
  $('#messages').append($('<li>').text(msg));
});
Conclusion

Socket.io is a powerful tool that enables us to build real-time applications with ease. It simplifies the process of creating a bi-directional communication channel between the server and the client, and provides us with various features such as automatic reconnection, broadcasting, room and namespace support.