Socket.io socket.emit没有将数据传递给服务器

时间:2016-04-25 04:36:35

标签: javascript socket.io

我正在尝试使用Socket.io。 我有以下代码。

这是我的index.html。

<!doctype html>
<html>
  <body>
    <ul id="messages"></ul>
    <form action="" onsubmit="return sayHello()">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script>
      var socket = io.connect('http://127.0.0.1:3001/');

    function sayHello(){
      var msg = document.getElementById('m');
      console.log(msg); <- This is getting printed. 
      socket.emit('message', msg.value);
      msg.value='';
      return (false);
    }

      // $('form').submit(function(){
      //   socket.emit('chat message', $('#m').val());
      //   $('#m').val('');
      //   return false;
      // });
      // socket.on('chat message', function(msg){
      //   $('#messages').append($('<li>').text(msg));
      // });
    </script>
  </body>
</html>

这是我的server.js

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

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log("GO!") <- This is getting printed
  socket.on('chat message', function(msg){
    console.log(msg); <- This is not getting printed. 
    io.emit('chat message', msg);
  });
});

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

我已经从Socket.io网站克隆了示例项目。我试图通过用VanillaJS替换Jquery来修改一些代码。

1 个答案:

答案 0 :(得分:0)

您正在侦听chat message,但会从客户端发出message。随.emit提供的事件名称必须与event处理程序中服务器上正在侦听的.on名称匹配。

//SERVER SIDE CODE
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
  console.log("GO!") < -This is getting printed
  socket.on('chat message', function(msg) {
    console.log(msg); < -This is not getting printed.
    io.emit('chat message', msg);
  });
});

http.listen(3001, function() {
  console.log('listening on *:3001');
});
<!doctype html>
<html>

<body>
  <ul id="messages"></ul>
  <form action="" onsubmit="return sayHello()">
    <input id="m" autocomplete="off" />
    <button>Send</button>
  </form>
  <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
  <script>
    var socket = io.connect('http://127.0.0.1:3001/');

    function sayHello() {
      var msg = document.getElementById('m');
      console.log(msg); < -This is getting printed.
      socket.emit('chat message', msg.value);
      //-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
      msg.value = '';
      return (false);
    }
  </script>
</body>

</html>