3

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

2
  • 1
    You ;) don't ;) need ;) all ;) those ;) winky ;) faces ;). (ps, this might be of help.) Commented Nov 1, 2016 at 0:18
  • Oh no! Where did all my smilies go? ;O I like to show my emotions.. hehe ;) Commented Nov 1, 2016 at 7:52

2 Answers 2

4

The simplest way is to emit object:

let users = []
let inout

function updateUsers() {
    io.emit('users', {users, inout});
}
Sign up to request clarification or add additional context in comments.

2 Comments

Arghh... so simple... Thanks... and for all noob proggers like me: on client side you then obviously have to separate these two objects in "data.users" and "data.inout"... thank you very much, Pasha :)
You're welcome. On the client you can destructure data object socket.on('users', ({users, inout}) => { /* ... */ })
0

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>

1 Comment

Thank you Robert, seems to be the same working solution as Pasha proposed.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.