简体   繁体   English

函数不适用于Socket.io

[英]A function does not work with Socket.io

I'm trying to send an array from a server that contains all the IDs of the users when someone connects on the server using socket io. 我正在尝试从服务器发送一个数组,当服务器使用socket io连接服务器时,该服务器包含用户的所有ID。 Apparently, the emitting part seems to work properly, but the receiving part is not responding at all. 显然,发射部分似乎工作正常,但接收部分根本没有响应。

io.sockets.on('connection',
// here's the on connection event
function (socket) {
  i++;
  ids[i]=socket.id;
  console.log("We have a new client: " + ids[i]);
  socket.broadcast.emit('setid', ids);
}
/////that is the emitting part

now this is the receiving part: 现在这是接收部分:

 socket.on('setid',
   function(ids) {
  console.log(ids);
 }
);

You need to change socket.broadcast.emit('setid', ids); 你需要改变socket.broadcast.emit('setid', ids); to socket.broadcast.emit('setid', {idArr:ids}); to socket.broadcast.emit('setid', {idArr:ids}); and console.log(ids.idArr); console.log(ids.idArr); on the receiving function. 在接收功能上。

as someone asked, 有人问,

Sever 断绝

io.on('connection',
// here's the on connection event
function (socket) {
  let i = 0;
  let ids = [];
  i++;
  ids[i]=socket.id;
  console.log("We have a new client: " + ids[i]);
  socket.broadcast.emit('setid', {
    idArr:ids
  });
}

Client 客户

socket.on('setid', function(ids) {
  console.log(ids.idArr);
 }
);

As a side note as It wasn't completely clear here, using socket.broadcast.emit shall emit to all clients except the socket sending the emit So until you open another client instance it won't emit. 作为旁注,因为这里还不完全清楚,使用socket.broadcast.emit将向除了发送发送的套接字之外的所有客户端发出 ,直到你打开另一个不会发出的客户端实例。

Look at the following example, it is very simple, just the socket.io server and the socket.io-client client (you may have to run npm install socket.io-client first): 看下面的例子,它非常简单,只是socket.io服务器和socket.io-client客户端(你可能必须首先运行npm install socket.io-client ):

khalil-server.js 哈利勒-server.js

const io = require('socket.io')(3001);
var ids = [];
io.on('connection', function (socket) {
    'use strict';
    ids.push(socket.id);
    console.log("We have a new client: " + socket.id);
    socket.broadcast.emit('setid', ids);
});
console.log('Server started at port 3001');

khalil-client.js 哈利勒-client.js

const socket = require('socket.io-client')('http://localhost:3001');
socket.on('setid', function (ids) {
    console.log(ids);
});

Start the server with node khalil-server and as many clients as you can with node khalil-client (you will have to run at least two client instances because we use the socket.broadcast.emit ). 使用node khalil-server启动服务器,并使用node khalil-client启动尽可能多的客户node khalil-client (您必须运行至少两个客户端实例,因为我们使用socket.broadcast.emit )。 It just works. 它只是有效。 Please show us more of your code and we will try to find a bug. 请向我们展示更多代码,我们将尝试查找错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM