简体   繁体   中英

How to send and receive data in sockets.io

I am stuck on something in sockets.io I want to send something to the server.js and then resend some of the data back out to everyone else connected.

So I would like to send something like

I have

userid="1"
username="dave"
message="some message"

So I would send it like :

userid:userid,
username:username,
message:message

At the moment I am only sending one paramater, 'message' like so :-

function sendmessage() {
    var new_message = document.getElementById("message").value;
    socket.emit('new_message', new_message);
}

and for the sever :

socket.on('new_message', function (data) {
    console.log(data);
    });

So I get the message ok but how do I send and receive and read the the rest and then send some of the data back out to everyone. Sorry but this is doing my head in and all the tutorials are just for sending msg.

To send a message to every socket connected : doc

io.emit('some event', { for: 'everyone' });

To answer your question about how to send multiple parameter, one way of doing this is to send an object with multiple keys.

function sendmessage() {
    socket.emit('new_message', { userid, username, message });
}

socket.on('new_message', function(data){
  console.log(`${data.userid} - ${data.username} - ${data.message} `);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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