服务端api来源网址:https://www.jianshu.com/p/8d28d3e0b43e
客服端api来源网址:https://www.jianshu.com/p/76ccda51a831
服务端api
io.on('connection', (socket) => {
// 发送给当前客户端
socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
// 发送给所有客户端,除了发送者
socket.broadcast.emit('broadcast', 'hello friends!');
// 发送给同在 'game' 房间的所有客户端,除了发送者
socket.to('game').emit('nice game', "let's play a game");
// 发送给同在 'game1' 或 'game2' 房间的所有客户端,除了发送者
socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
//发送给在线的所有客户端
io.emit('new message', 'an event sent to all connected clients');
// 发送给同在 'game' 房间的所有客户端,包括发送者
io.in('game').emit('big-announcement', 'the game will start soon');
// 发送给同在 'myNamespace' 命名空间下的所有客户端,包括发送者
io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
// 发送给指定 socketid 的客户端(私密消息)
io.to(<socketid>).emit('hey', 'I just met you');
// 包含回执的消息
socket.emit('question', 'do you think so?', function (answer) {});
// 不压缩,直接发送,默认压缩
socket.compress(false).emit('uncompressed', "that's rough");
// 发送给当前 node 实例下的所有客户端(在使用多个 node 实例的情况下)
io.local.emit('hi', 'my lovely babies');
};
客服端api
io.on('connection', (socket) => {
// 输出websocket分配的客服端ip
console.log(this.id);
// 接收服务端的
socket.on('add user', ({userName}, fn) => {
fn('receive data');
});
//客户端监听用户加入聊天室
socket.on('user joined', ({userName, count}) => {
})
});
// 设置修改器,是否对向服务器传输的数据进行压缩。默认为true,即压缩
socket.compress(false).emit('add user', { userName: 'ningxiaojie' });
//断开连接时触发事件处理器
socket.on('disconnect', (reason) => {
// ...
});
//重连成功时触发事件处理器
socket.on('reconnect', (attempt) => {
// ...
});
//尝试重连时触发事件处理器
socket.on('reconnect_attempt', (attempt) => {
// ...
});
//尝试重连时触发事件处理器
socket.on('reconnecting', (attempt) => {
// ...
});
//重连错误时触发事件处理器
socket.on('reconnect_error', (error) => {
// ...
});
//重连失败时触发事件处理器
socket.on('reconnect_failed', () => {
// ...
});
//手动关闭客户端对服务器的链接
socket.close()
Vue客服端引入(请看我的这篇文章,写了socket.io在vue中引入时遇到的坑)
https://blog.youkuaiyun.com/qq8344310/article/details/98873948
本文详细解析了Socket.IO的服务端与客服端API,涵盖了消息发送、接收、事件处理、重连机制及客户端状态监测等核心功能。通过具体代码示例,帮助开发者快速掌握Socket.IO的使用技巧。
5216

被折叠的 条评论
为什么被折叠?



