WebSocket协议-Socket.io 服务端API和客服端API与vue中的使用

服务端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.csdn.net/qq8344310/article/details/98873948

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值