Technology Sharing

WebSocket、socket.io-client

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

WebSocket

WebSocket is a network communication protocol that provides a channel for full-duplex communication over a single long-lasting TCP connection.

WebSocket allows two-way data exchange between the client and the server, which means that the server can actively push data to the client without having to wait for the client's request. After the WebSocket connection is established, both the client and the server can send data at any time, which greatly improves real-time and interactivity.

socket.io-client

When used on the front end, you can directlynew WebSocketTo use, but use the nativeWebSocketThe functions provided are relatively simple and require some handling by yourself. This is availablesocket.io-clientTo operate

socket.io-client Compared to the native WebSocket API, it provides richer features and wider compatibility, which makes it a better choice in many cases.socket.io-client Some of the main advantages:

  1. compatibility:
    socket.io-client Automatically fall back to other transports such as long-polling, Flash Sockets, etc. in browsers that don't support WebSocket, ensuring that it works in almost all modern browsers and some older browsers.

  2. Automatic reconnection:
    When the network connection is interrupted or the server is restarted,socket.io-client Can automatically try to reconnect, while native WebSocket requires manual handling of reconnection logic.

  3. Error handling:
    socket.io-client Provides a more complete error handling mechanism to better report and handle network errors.

Basic Use

socket.io-client It is a library for communicating with a Socket.IO server on the client (usually a browser or Node.js application). It provides a powerful API that can handle real-time two-way communication, including automatic reconnection, heartbeat detection, error handling and other functions.

Install

First, you need to install socket.io-client. Run the following command in your project directory:

npm install socket.io-client
  • 1

Importing modules

In your JavaScript file, you can use ES6 module import method to import socket.io-client

import { io } from 'socket.io-client';
  • 1

Or, if you're using CommonJS modules:

const io = require('socket.io-client');
  • 1

Creating a Socket Instance

Creating a Socket instance usually requires passing in the server URL. This can be a relative path (for the same domain name) or a complete URL (for cross-domain connections). For example:

const socket = io('http://localhost:3000');
const socket = io('https://yourdomain.com');
const socket = io("wss://server-domain.com");
  • 1
  • 2
  • 3

Listening for events

Once you create a Socket instance, you can listen for various events, such as connection status changes, received messages, etc.

socket.on('connect', () => {
  console.log('Connected to server');
});

socket.on('disconnect', (reason) => {
  console.log('Disconnected from server', reason);
});

socket.on('message', (data) => {
  console.log('Received message from server', data);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

send data

you can use emit Method to send events and data to the server.

socket.emit('chat message', { message: 'Hello from the client!' });
  • 1

Disconnect

When the connection is no longer needed, you can explicitly close the Socket connection:

socket.disconnect();
  • 1

Complete Example

Here is a complete example showing how to use it on the client side socket.io-client

import { io } from 'socket.io-client';

// 创建 Socket 实例
const socket = io('http://localhost:3000');

// 监听连接事件
socket.on('connect', () => {
  console.log('Connected to server');
});

// 监听接收消息事件
socket.on('message', (data) => {
  console.log('Received message from server', data);
});

// 发送消息到服务器
socket.emit('chat message', { message: 'Hello from the client!' });

// 当组件销毁时,关闭 Socket 连接
// 如果你是在 Vue 或 React 的生命周期钩子中使用,确保在这里调用 disconnect
// 或者使用适当的事件来触发断开连接
// socket.disconnect();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22