bernd pfeffer
bernd pfeffer

Reputation: 33

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

Learning Node.js, Express.js and 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

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... ;)

Upvotes: 3

Views: 21998

Answers (2)

Paul Rumkin
Paul Rumkin

Reputation: 6883

The simplest way is to emit object:

let users = []
let inout

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

Upvotes: 4

RobertAKARobin
RobertAKARobin

Reputation: 4258

I think you need to read the documentation more clearly, because this doesn't look like 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>

Upvotes: 0

Related Questions