NodeJS和socket.io无法发送消息

时间:2015-02-19 08:17:06

标签: node.js sockets amazon-ec2

服务器:

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

var clients = [];
var sequence = 1;

io.on('connection', function(socket){

    console.log('Client connected (id=' + socket.id + ').');
    clients.push(socket);

    socket.on('login', function(msg){
        console.log(msg);
        io.emit('login', msg);
    });

    socket.on('disconnect', function(){
        var index = clients.indexOf(socket);
        if (index != -1) {
            clients.splice(index, 1);
            console.info('Client gone (id=' + socket.id + ').');
        }
    });

});

http.listen(3011, function(){
  console.log('listening on *:3011');
});

客户端:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io('http://localhost:3011');
      $('form').submit(function(){
        socket.emit('login', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('login', function(msg){
        //alert(msg);
        $('#messages').append($('<li>').text(msg));
      });


      socket.on('connect', function() { 
          console.log('connected');
       });

       socket.on('message', function(msg){
          console.log(msg);
       });

       socket.on('disconnect', function() {
          console.log('disconnected');
       });

       socket.on('error', function (e) {
          console.log('System', e ? e : 'A unknown error occurred');
       });


    </script>
  </body>
</html>

这项工作在localhost上非常完美。 服务器日志:

listening on *:3011
Client connected (id=Kk-LUoJep5Uw0qWLAAAA).
message
Client gone (id=Kk-LUoJep5Uw0qWLAAAA).

但是,如果我使用ec2服务器。 NodeJS和socket.io无法发送消息。 log ec2 server:

listening on *:3011
Client connected (id=1Phd18CNKLEnRH3LAAAA).
Client gone (id=1Phd18CNKLEnRH3LAAAA).

港口3011开放。 enter image description here

他正在获取连接和断开事件,但无法获取或发送消息。 怎么解决?谢谢。

0 个答案:

没有答案