简体   繁体   English

socket.io:如何同时发出数组和变量

[英]socket.io: How to emit an Array and a Variable simultaneously

Learning Node.js, Express.js and Socket.io.学习 Node.js、Express.js 和 Socket.io。

Made a Chat an it works so far.制作了一个聊天,到目前为止它有效。

Now I would like to emit to the Client, that a user has entered or left the chat by emiting a variable that indicates that...现在我想向客户端发出一个用户已经进入或离开聊天的信息,该变量通过发出一个指示......

Ist that possible?这可能吗?

So something like this:所以像这样:

Server.js服务器.js

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

Client:客户:

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

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

Thanks for any Help... ;)感谢您的帮助...;)

The simplest way is to emit object:最简单的方法是发出对象:

var users=[]
var inout

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

I think you need to read the documentation more clearly, because this doesn't look like Socket.io.我认为您需要更清楚地阅读文档,因为这看起来不像 Socket.io。

Here's an example of sending an array, along with some other data:这是发送数组以及其他一些数据的示例:

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>

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

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