socket.on及socket.emit方法

论坛 期权论坛 脚本     
已经匿名di用户   2022-7-2 21:58   1176   0

WebScoket是一种让客户端和服务器之间能进行双向实时通信的技术。它是HTML最新标准HTML5的一个协议规范,本质上是个基于TCP的协议,它通过HTTP/HTTPS协议发送一条特殊的请求进行握手后创建了一个TCP连接,此后浏览器/客户端和服务器之间便可以通过此连接来进行双向实时通信。

socket.io 是基于 Node.js WebSocket 协议的实时通信开源框架,它包括客户端的JavaScript和服务器端的Node.js。WebSocket是SocketIO的一个子集。

emit 和 on

Socket.IO服务器具有一个sockets属性,属性值为所有与客户端建立连接的socket对象。可以利用该对象的send方法或者emit方法向所有客户端广播消息。emiton 是最重要的两个 API,分别对应 发送监听 事件。我们可以非常自由的在服务端定义并发送一个事件emit,然后在客户端监听 on,反过来也一样。

emit的使用方式

搭一个server服务器

var server = require('http').createServer((req, res) => {
res.end("111")
});
var io = require('socket.io')(server);
server.listen(9002);

在发生特定情况时发送一个action命令

a)命令可以只有一个名字

  io.emit('自命名')

  b)命令可以除了名字还有数据

    io.emit('自命名',a)

  c)命令可以除了名字还有多个数据

    io.emit('自命名',a,b,c,...,d)

  d)命令可以除了名字还有回调函数

    io.emit('自命名',data,function(a,b){ } )

此时对应接收数据的地方应该建议与socket的链接

var socket = io('http://localhost:9002');
socket.on('msg', function (msg) {
  location.reload();
});

此时的socket.on与上述2一一对应

  a)命令可以只有一个名字

    socket.on('自命名',function(){ } )

  b)命令可以除了名字还有数据

    socket.on('自命名', function(data){ } )

  c)命令可以除了名字还有多个数据

    socket.on('自命名', function(a,b,c,...,d){ } )

  d)命令可以除了名字数据还有回调函数

    socket.on('自命名', function(data,fn){ fn(a,b); })

emit的常见用法

io.on('connect', onConnect);

function onConnect(socket){

  // 只发给sender。 sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // 发给所有人,除了sender。 sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // 发给game房间所有人,除了sender。 sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // 发给game1和/或game2所有人,除了sender。 sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // 发给game房间所有人,包含sender。 sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // 发给域名myNamespacs所有人,包含sender。 sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // 发给域名myNamespace里room房间的所有人,包含sender。 sending to a specific room in a specific namespace, including sender
  io.of('myNamespace').to('room').emit('event', 'message');

  // 发给某一个人 sending to individual socketid (private message)
  io.to(`${socketId}`).emit('hey', 'I just met you');


};

详情链接:https://blog.csdn.net/nathanhuang1220/article/details/41348213?utm_source=blogxgwz1

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP