我一定是在做一些非常愚蠢的事情,因为http://socket.io/get-started/chat/上针对 Node.JS 和 Socket.IO的教程(!)聊天示例对我不起作用。更具体地说,当我加载网页时,“连接”事件没有触发。
这是完整的 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');
});
http.listen(3000, function(){
console.log('1e listening on *:3000');
});
这是完整的 index.html:
<!doctype html>
<html>
<head>
<title>1e 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>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://X.YY.ZZZ.QQ:3000');
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
防火墙信息:
- 在 X.YY.ZZZ.QQ:3000 上,我禁用了防火墙(是的,快速而丑陋的临时黑客以避免超时并加载页面,直到我弄清楚如何正确设置 iptables 规则)通过
service iptables stop
- 在本地 Windows 机器上,我可以通过 ssh 轻松访问 X.YY.ZZZ.QQ,并且在 Windows 中也禁用了防火墙,所以我认为端口在这里应该不是问题
什么有效:
- 客户端:我可以通过 InternetExplorer 访问 X.YY.ZZZ.QQ:3000,它会显示带有发送按钮的聊天栏。
- 我确定 index.html 是正在加载的文件,因为我会在每次更改 html 文件时不断更改标题标签(“1e”)
- 服务器:控制台输出在通过命令 ./node index.js 启动时显示 *"1e listener on .3000 "
- 我还不断更改版本(“1e”)以确保 node.js 文件是正确的
什么不起作用:
- 我应该在(重新)加载网页选项卡时收到控制台消息“用户已连接”,但它没有触发。我在 var socket = io.connect () 行的 HTML 代码中放了一个断点,它确实执行了该行,所以看起来 socket.io 正在加载
有没有错误代码?你如何对 Node.JS/Socket.IO 进行故障排除?有内部日志吗?我看了,但没有看到。
我很确定我忽略了一些非常原始的东西,但是由于这种网络技术对我来说是新的(我主要是 C/C++ 人),我迷路了。有任何想法吗 ?