socket.io Events整理
服务器端
初始化:
const options = { /* ... */ };
const io = require('socket.io')(options);
io.on('connection', socket => {
/* ... */
socket.on('error',()=>{});
socket.on('disconnecting',()=>{});
socket.on('disconnect',()=>{});
});
io.listen(3000);
事件:
disconnect:断开连接
error:发生错误
disconnecting:正在断开
客户端
初始化:
import io from 'socket.io-client';
const socket = io();
console.log(socket.connected); // false
socket.on('connect', () => {
console.log(socket.connected); // true
});
socket.on('disconnect', () => {
console.log(socket.connected); // false
});
事件:
connect:连接成功 [Fired upon connection (including a successful reconnection)]
disconnect:断开连接 [Fired upon disconnection]
connect_error:连接错误 [Fired upon a connection error]
connect_timeout:连接超时 [Fired upon a connection timeout]
error:发生错误 [Fired when an error occurs]
reconnect:成功重连 [Fired upon a successful reconnection]
reconnect_attempt:尝试重连[Fired upon an attempt to reconnect]
reconnecting:正在重连 [Alias for “reconnect_attempt”]
reconnect_error:重连错误 [Fired upon a reconnection attempt error]
reconnect_failed:重连失败 [Fired when the client couldn’t reconnect within reconnectionAttempts]
ping:发送ping消息事件 [Fired when a ping is sent to the server]
pong:接受到pong消息 [Fired when a pong is received from the server]
事件触发举例:
当失去连接时,事件触发顺序为:disconnect->reconnecting(多次尝试建立连接)->reconnect->connect。


浙公网安备 33010602011771号