socket.emit 和 socket.on 在 node.js 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17663589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:02:27  来源:igfitidea点击:

socket.emit and socket.on do not work in node.js

node.jssocket.io

提问by Hsm Sharique Hasan

I tried to connect my chrome browser to NodeJs Server. All the code works great on other machine. but when i run it on my machine neither it gives an error nor it gives a success. here is the code

我试图将我的 chrome 浏览器连接到 NodeJs 服务器。所有代码在其他机器上运行良好。但是当我在我的机器上运行它时,它既不出错也不成功。这是代码

Server Code:

服务器代码:

var server =  http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(server);
io.sockets.on('message', function (socket) {
    socket.emit('news', { hello: 'world' });

});

and Here is the Client Code.

这是客户代码。

<script>
        var socket = io.connect('http://localhost:3000/');
       //console.log(socket);
        socket.on("message",function(data){
            console.log(data);
        })
    </script>

Kindly correct me where I am doing it wrong. console.log() in client doesnot work. I tried to check it in chrome debugger using breakpoints but it never goes to that point.

请纠正我做错的地方。客户端中的 console.log() 不起作用。我尝试使用断点在 chrome 调试器中检查它,但它永远不会到达那个点。

回答by leko

You are missing some code:

您缺少一些代码:

io.sockets.on('connection', function (socket) {
  socket.on('message', function (data) {
    socket.emit('news', { hello: 'world' });
  });

  socket.on('another-message', function (data) {
    socket.emit('not-news', { hello: 'world' });
  });
});

Taken from socket IOwebsite. For this to work you need to start by sending a 'message' from the client, something in the lines of:

取自套接字 IO网站。为此,您需要首先从客户端发送“消息”,内容如下:

<script>
  var socket = io.connect('http://localhost:3000/');
  socket.on('connect',function(){
    socket.emit('message', 'Hello server');
  });

  socket.on('news', function(msg) {
    alert('News from server: ' + msg.hello);
  });
</script>