Socket.io: Node.js 无法通过 AWS 上的方法 socket.on('message', ...) 接收事件消息

Socket.io: Node.js can't receive event message via method socket.on('message', ...) on AWS

即使 the Socket.io official chat sample 我也有这个问题。

我在 AWS 上设置了这个。我只能在终端上收到 'successfully connected' 消息,但收不到 'message: ....'。即使使用 Google 开发工具,我也看不到任何相关错误。有人可以帮忙吗?

这是客户端javascript代码:

  <script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
  <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  <script>
    var socket = io();
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
  </script>

然后服务器端node.js代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});
http.listen(8989, function(){
  console.log('listening on *:8989');
});

io.on('connection', function(socket){
  console.log('successfully connected');
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

单击按钮时没有表单提交,表单提交也会创建大量页面刷新和所有内容,而且您不需要此练习的表单

创建函数sendMessage()

<script>
    var socket = io();
    function sendMessage(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
    }
</script>

在您的 HTML 中删除表单并将 onclick 添加到按钮

<body>
    <ul id="messages"></ul>
    <input id="m" autocomplete="off" /><button onclick="sendMessage()">Send</button>
</body>

原来问题出在客户端 javascript 代码上。

我参考了this sample code,发现在socket.io官方网站上它说在某些情况下(Express 3/4或框架)你需要使用io.connect()来代替的 io()。但是在我之前的案例中它对我有用。

这是更改后的代码:

var socket = io.connect();
$('form').submit(function(){
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
});