Socket.io – 无法从客户端发送消息到服务器端

我有两个文件 –

  • 的index.html
  • index.js

index.html中 ,我有一个文本框。 我想在文本框上显示input到控制台的消息(node.js的命令提示符)。

在这里输入图像说明

index.html中 ,我写了这个 –

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

在服务器端,在index.js中我使用了这个 –

 socket.on('chat message', function(msg){ //here is the listener to the event console.log('message: ' + msg); }); 

但是,消息没有显示在控制台中。 我的代码有什么问题? 如果需要请参考下面的文件。

index.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('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat message', function(msg){ //here is the listener to the event console.log('message: ' + msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); 

的index.html

 <!doctype html> <html> <head> <title>Socket.IO chat</title> <style> //some code </style> </head> <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(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); </script> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> </body> </html> 

在closures</body>标记前移动包含socket.io代码的html文件中的<script>块,以便只在主体完成加载后加载脚本。