简体   繁体   English

socket.on()不接收数据

[英]socket.on() not receiving data

I am having a problem with getting socket.on to work 我在使用socket.on上班时遇到问题

$('#showmsg').click(function() {
var socket = io.connect('http://localhost:3000');
var msgText = $('#msgtext');
socket.emit('show msg', msgText.val());
});

That code works, as shown by using 该代码有效,如通过使用所示

io.sockets.on('connection', function(socket) {
    socket.on('show msg', function(data) {
        console.log(data);
    });
});

in server.js, my main app file, however in another file, when I use the code 在server.js中,是我的主应用程序文件,但是在另一个文件中,当我使用代码时

    $(document).ready(function (){
        var socket = io.connect();
        socket.on('show msg', function(data) {
            $('#container').hide();
        });
    });

Nothing happens. 什么都没发生。 Does anyone know how I can get this code to work? 有谁知道我如何使此代码起作用?

When you connect in the client, you have to wait for the connect message before you can send data with .emit() . 在客户端中进行连接时,必须等待connect消息,然后才能使用.emit()发送数据。 As you have it now, you are trying to send the data before the connection has finished so the data is lost. 现在,您正在尝试在连接完成之前发送数据,从而导致数据丢失。

See the client-side example here: http://socket.io/docs/#sending-and-getting-data-(acknowledgements) 请参阅此处的客户端示例: http : //socket.io/docs/#sending-and-getting-data-(致谢)

I think what's happening is that in your document.ready function, you are trying to call io.connect() but you are then calling the show message before your socket has connected. 我认为正在发生的事情是在document.ready函数中,您尝试调用io.connect(),但是随后在套接字连接之前调用show消息。 Try doing it like this 尝试这样做

socket.on('connect', function (){
   socket.on('show msg', function(data) {
        $('#container').hide();
    });
});

Nothing happens because you don't emit anything. 什么也没发生,因为您什么都不发出。

$(document).ready(function (){
  var socket = io.connect('http://localhost:3000');
  socket.on('show msg', function(data) {
    $('#container').hide();
  });
  socket.emit('show msg', 'right now I am emitting data');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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