Node.js socket.io函数不在服务器和客户端之间发送

首先我想就我的问题中的任何错误道歉,这是我的第一个家伙!

我正在尝试使用下面的代码来testing我的服务器和客户端之间的连接。

这是如何工作:一个套接字启动在某个端口,然后客户端尝试连接到该端口,连接部分成功,这意味着“节点server.js”启动连接,当我在我的浏览器上的本地主机:8000'的HTML页面生成,但是当我点击button什么都没有发生。

index.html代码

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> $(document).ready(function() { var socket = io.connect("localhost:8000"); $("#join").click(function() { var name = $("#name").val(); if (name != "") { socket.emit("join", name); } }); socket.on("update", function(msg) { $("#msgs").append("<li>" + msg + "</li>"); }); }); </script> </head> <body> <input type="text" placeholder="Yor name" id="name"> <input type="button" name="join" id="join" value="Join!"> <ul id="msgs"> </ul> </body> 

server.js代码

 var fs = require('fs'), http = require('http'), sio = require('socket.io'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); }); server.listen(8000, function() { console.log('server is running'); }); var socket = sio.listen(server); socket.on("connection", function (client) { client.on("join", function(name) { client.emit("update", name + "You have successfully sent your first message."); }); }); 

你给variables命名的方式让人感到困惑。 你的代码唯一的问题是这个代码:

 socket.on('connection', handler); 

应改为:

 socket.sockets.on('connection', handler); 

在大多数情况下,以及网站上的示例, EventEmitter通常会被命名为io.sockets 。 在你的情况下,你正在做相当于io.on('connection', handler); 这就是为什么它不能正常工作。