🗒️WebSocket

原生的

const socket = new WebSocket(ws_url)

// 监听事件
socket.onopen = () => { }
socket.onclose = () => { }
socket.onerror = () => { }
socket.onmessage = (event) => {
    let data = JSON.parse(event.data)  // 接收数据 event.data
}

// 调用方法
socket.close()

SocketIO

使用,代码示意:

// https://github.com/socketio/socket.io-client/blob/master/docs/API.md
// https://github.com/socketio/engine.io-client#methods
import io from 'socket.io-client'

class SocketIO {
    
    socket;

    constructor(){
	this.socket = io(
	    ws_origin,            // url 默认是 window.location
	    {  
		path: ws_path,    // String. 默认是 '/socket.io'
		// query: {},     // Object. 查询参数
		// parser:;       // 使用的解析器。默认是 socket.io 自带的 Parser。详见 socket.io-parser
		// reconnection: true,           // Boolean. 是否自动重新连接。默认 true
		// reconnectionAttempts: 1,      // Number. 尝试重新连接的次数。默认 Infinity
		// reconnectionDelay: 1000,      // Number. 尝试重新连接之前的等待多长。默认 1000。但它受随机因子影响,比如默认的初始延时会介于 500-1500 ms
		// reconnectionDelayMax: 5000,   // Number. 重新连接之间等待的最长时间。默认 5000。每次尝试都将重新连接延迟增加2倍以及随机化
		// randomizationFactor: 0.5,     // Number. 默认 0.5。 0 <= randomizationFactor <= 1
		// timeout: 20000,               // Number. 连接超时, 默认 20000。  如果多长时间之内连接还没建成功,则认为失败,会触发 connect_error 和 connect_timeout 事件。进而触发重连机制
		autoConnect: autoConnect,            // Boolean. 默认是 true。如果设置成 false,则必须手动调用 manager.open,在你觉得合适的时候
		transports: ['websocket', 'polling']    // Array. 要尝试的传输列表(按序)。默认是 ['polling', 'websocket']。
	})
		
	// 监听事件
	// this.socket.on('connect', () => {})
	// this.socket.on('connect_error', (error) => {})
	// this.socket.on('connect_timeout', (error) => {})
	// this.socket.on('reconnect', (attemptNumber) => {})
	// this.socket.on('disconnect', (reason) => {})
	// this.socket.on('error', (error) => {})
	// this.socket.on('ping', () => {
	//    console.warn('套接字: ping')
	// })
	// this.socket.on('pong', (latency) => {
	//    console.warn('套接字: pong')
	// })
	
	// 监听服务器推送的消息(自定义类型)
	socket.on('REPLY', (res) => {
	    let data = JSON.parse(res) // 再传给对应的函数
	})
	socket.on('END', (res) => {
	    let data = JSON.parse(res) // 再传给对应的函数
	})
	socket.on('DRAWBACK', (res) => {
	    let data = JSON.parse(res) // 再传给对应的函数
	})
    }
}

对外 API,代码示意:

centrifuge-js

使用上:若用户登录了,则开始连接:先 new,再 subscribe 再 connect。代码示意:

对外提供的接口,有三类,代码示意如下。

Last updated