无法将数据从套接字发送到特定客户端

时间:2019-09-05 09:34:52

标签: javascript html node.js sockets socket.io

我正在使用套接字将数据发送到特定的客户端,但是在客户端,我无法获取数据。

我正在此行发送数据

io.to("user1@example.com").emit('new_msg', {msg: 'hello'});

并使用此代码在客户端上接收

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

这是我的完整代码,JS和HTML文件。

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("user1@example.com").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: "user1@example.com"});
 });

  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: "user1@example.com"});
 });
</script>

我也收到连接成功消息,也从客户端到服务器获取数据 enter image description here

1 个答案:

答案 0 :(得分:2)

问题是您从未加入会议室,而是在此处向该会议室发送消息

 io.to("user1@example.com").emit('new_msg', {msg: 'hello'});

内部加入方法让客户加入房间

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