Nodejs Socket.IO 内置事件
Nodejs Socket.IO 内置事件
在看一些Socket.IO的文章,都有提到自定义事件命名不要和内置事件冲突,但是找遍了也没有个权威的内置事件有哪些的说明。 目前知道的有connection,disconnect,message这三个…
又翻了一些文章 这个写的比较详细:http://raytaylorlin.com/Tech/web/Node.js/socket-io-advanced/ 事件
Socket.IO内置了一些默认事件,我们在设计事件的时候应该避开默认的事件名称,并灵活运用这些默认事件。
服务器端事件:
io.sockets.on(‘connection’, function(socket) {}):socket连接成功之后触发,用于初始化 socket.on(‘message’, function(message, callback) {}):客户端通过socket.send来传送消息时触发此事件,message为传输的消息,callback是收到消息后要执行的回调 socket.on(‘anything’, function(data) {}):收到任何事件时触发 socket.on(‘disconnect’, function() {}):socket失去连接时触发(包括关闭浏览器,主动断开,掉线等任何断开连接的情况) 客户端事件:
connect:连接成功 connecting:正在连接 disconnect:断开连接 connect_failed:连接失败 error:错误发生,并且无法被其他事件类型所处理 message:同服务器端message事件 anything:同服务器端anything事件 reconnect_failed:重连失败 reconnect:成功重连 reconnecting:正在重连 在这里要提下客户端socket发起连接时的顺序。当第一次连接时,事件触发顺序为:connecting->connect;当失去连接时,事件触发顺序为:disconnect->reconnecting(可能进行多次)->connecting->reconnect->connect。
Nodejs Socket.IO 内置事件
在使用Socket.IO进行开发时,了解内置事件是非常重要的,因为这可以帮助我们避免与Socket.IO框架中的默认事件名称冲突,从而确保应用的正常运行。
服务器端事件
-
connection
- 当客户端连接到服务器时触发。
io.on('connection', (socket) => { console.log('A user connected'); // 可以在这里执行一些初始化操作 });
-
disconnect
- 当客户端断开连接时触发,包括关闭浏览器、主动断开连接或网络问题导致的断开。
socket.on('disconnect', () => { console.log('A user disconnected'); });
-
message
- 当客户端发送消息时触发。
socket.on('message', (data, callback) => { console.log('Message received:', data); // 可以在这里处理消息并发送响应 callback('Server received your message'); });
-
anything
- 当接收到任何事件时触发。
socket.on('anything', (data) => { console.log('Any event received:', data); });
客户端事件
-
connect
- 当客户端成功连接到服务器时触发。
const socket = io(); socket.on('connect', () => { console.log('Connected to server'); });
-
disconnect
- 当客户端断开连接时触发。
socket.on('disconnect', () => { console.log('Disconnected from server'); });
-
connect_failed
- 当客户端连接尝试失败时触发。
socket.on('connect_failed', () => { console.log('Connection failed'); });
-
error
- 当发生错误时触发。
socket.on('error', (err) => { console.error('Error occurred:', err); });
-
message
- 当从服务器接收到消息时触发。
socket.on('message', (data) => { console.log('Message from server:', data); });
-
anything
- 当接收到任何事件时触发。
socket.on('anything', (data) => { console.log('Any event received:', data); });
-
reconnect
- 当客户端成功重新连接到服务器时触发。
socket.on('reconnect', () => { console.log('Reconnected to server'); });
-
reconnecting
- 当客户端正在尝试重新连接时触发。
socket.on('reconnecting', (attemptNumber) => { console.log(`Reconnecting attempt ${attemptNumber}`); });
-
reconnect_failed
- 当客户端的重新连接尝试失败时触发。
socket.on('reconnect_failed', () => { console.log('Failed to reconnect'); });
连接流程
当客户端首次连接时,事件触发顺序为:
connecting
->connect
当客户端断开连接时,事件触发顺序为:
disconnect
->reconnecting
(可能进行多次) ->connecting
->reconnect
->connect
通过理解这些内置事件及其触发时机,我们可以更好地管理Socket.IO连接,确保应用的稳定性和健壮性。
我想你想多了