Ad

Not Able To Send Data From Socket To Specific Client

- 1 answer

I am sending data to a specific client with a socket but on client-side, I am not able to get data.

I'm sending data at this line

io.to("[email protected]").emit('new_msg', {msg: 'hello'});

and receive on client with this code

socket.on("new_msg", function(data) {
    console.log("here")
    alert(data.msg);
   })

Here is my full code, JS and HTML file.

JS:

var io = require('socket.io')();


io.sockets.on('connection', function(client) {
    console.log('Client connected...', client.id);

    client.on('join', function(data) {
            console.log(data.email);
    });

    client.on('messages', function(data) {
        client.emit('broad', data);
        io.to("[email protected]").emit('new_msg', {msg: 'hello'});
    });

})

io.listen(3000);

HTML:

<!doctype html>
<html lang="en">
    <head>

    </head>
    <body>
        <h1>Hello World!</h1>
        <div id="future"></div>
        <form id="form" id="chat_form">
            <input id="chat_input" type="text">
            <input type="submit" value="Send">
        </form>
         <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
    </body>
</html>

<script>
 var socket = io.connect('http://127.0.0.1:3000');
 socket.on('connect', function(data) {
    socket.emit('join', {email: "[email protected]"});
 });

  socket.on('broad', function(data) {
         $('#future').append(data+ "<br/>");
   });

  socket.on("new_msg", function(data) {
    console.log("here")
    alert(data.msg);
   })

 $('form').submit(function(e){
     e.preventDefault();
     var message = $('#chat_input').val();
     socket.emit('messages', {email: "[email protected]"});
 });
</script>

I also get a connection success message and also get data from client to server enter image description here

Ad

Answer

The problem is you never joined the room and you are emitting the message to that room here

 io.to("[email protected]").emit('new_msg', {msg: 'hello'});

Inside join method let the client join the room

client.on('join', function(data) {
        console.log(data.email);
       client.join(data.email)
});
Ad
source: stackoverflow.com
Ad