【问题标题】:socket.io: How to emit an Array and a Variable simultaneouslysocket.io:如何同时发出数组和变量
【发布时间】:2017-03-14 03:13:50
【问题描述】:

学习 Node.js、Express.js 和 Socket.io。

进行了一次聊天,到目前为止它有效。

现在我想向客户端发出用户已经进入或离开聊天的信息,方法是发出一个变量来指示...

这可能吗?

所以是这样的:

服务器.js

var users = [];
var inout;
function updateUsers(){
    io.emit('users', users, 'inout', inout);
}

客户:

var socket = io.connect( 'http://'+window.location.hostname+':3000' );
    socket.on('users', function(data){

// how to get the 'inout' here? }

感谢您的帮助... ;)

【问题讨论】:

  • 你 ;) 不需要 ;) 需要 ;) 所有 ;) 那些 ;) 眨眼 ;) 面孔 ;)。 (ps,this 可能会有所帮助。
  • 哦不!我所有的笑脸都去哪儿了? ;O 我喜欢表达我的情绪.. 呵呵 ;)

标签: javascript node.js sockets express


【解决方案1】:

最简单的方法是发射对象:

let users = []
let inout

function updateUsers() {
    io.emit('users', {users, inout});
}

【讨论】:

  • Arghh... 这么简单... 谢谢... 对于所有像我这样的新手:在客户端,您显然必须在“data.users”和“data”中分离这两个对象.inout"...非常感谢你,帕夏 :)
  • 不客气。在客户端你可以解构数据对象socket.on('users', ({users, inout}) => { /* ... */ })
【解决方案2】:

我认为你需要更清楚地阅读documentation,因为这看起来不像 Socket.io。

这是一个发送数组以及其他一些数据的示例:

var io = require("socket.io")(3001);
io.emit("myEvent", {
  somethingToSendToBrowser: "Hello",
  arrayToSendToBrowser: [
    "I'm the data that will get sent.",
    "I'm some more data.",
    "Here's the third piece of data."
  ]
});

<script src="/node_modules/socket.io-client/socket.io.js"></script>
<script>
var socket = io("http://localhost:3001");
socket.on("myEvent", function(data){
  console.log(data.arrayToSendToBrowser);
  // ["I'm the data that will get sent.", "I'm some more data.", "Here's the third piece of data.]"
});
</script>

【讨论】:

  • 谢谢罗伯特,似乎与 Pasha 提出的解决方案相同.. :)
猜你喜欢
  • 2021-05-30
  • 2020-04-16
  • 2012-02-10
  • 2017-09-22
  • 2019-04-01
  • 2019-05-27
  • 2020-06-27
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多