我是 node.js 和 socket.io 的新手,并尝试使用 http://socket.io/#how-to-use 中的示例将服务器连接到客户端。 。 (无本地主机)
服务器:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html'+err);
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.broadcast.send(msg);
});
socket.on('disconnect', function () { });
});
客户:
<html><head><script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connect', function () {
alert('connected.');
socket.on('message', function (msg) {
// my msg
alert('message received: '+msg);
});
socket.send('hi');
});
</script>
</head><body>This is the content :)</body>
</html>
Google Chrome 在控制台中显示:
Unexpected response code: 502
此外,Chrome 在收到每条消息后都会添加
GET http://[myServer]/socket.io/1/?t=1352313105809 socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
maybeReconnect
到控制台。 问题出在哪里?
最佳答案
操作方法页面中的示例均使用端口 80,这对于服务网站来说很常见。
但是,您在示例中使用端口 8080。
检查您的网络浏览器的控制台是否加载了 socket.io 脚本。
您可能需要提供 http://localhost:8080/socket.io/socket.io.js
作为显式 url 并使用 io.connect('http://localhost:8080 ');
如果上述方法不起作用,请分享一些有关您的网络服务器运行端口的见解。
<小时/>在您的(更新的)示例中,没有代码可以实际处理服务器端的任何传入消息。
`socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.send(msg);
});
至少应该将消息发送回客户端 - 仅当客户端收到消息时才会触发警报。 Node.js 控制台是否输出任何传入或发送的消息?连接后,我的 Node.js 控制台的几行如下所示。
debug - client authorized
info - handshake authorized ...
debug - setting request GET /socket.io/1/...
debug - set heartbeat interval for client ...
debug - client authorized for
debug - websocket writing 1::
debug - sending data ack packet
关于javascript - Node.js + socket.io : app on server not working correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222232/