【发布时间】:2012-04-19 07:31:07
【问题描述】:
我正在尝试开始使用 node.js 和 socket.io。
我有一个非常(非常)简单的客户端-服务器测试应用程序,但我无法让它工作。
该系统设置在一台装有 apache 服务器的 windows 机器上。
apache 在port 81 上运行,socket.io 设置为监听port 8001
服务器 - server.js
var io = require('socket.io').listen(8001);
io.sockets.on('connection', function (socket) {
console.log('\ngot a new connection from: ' + socket.id + '\n');
});
客户端 - index.html
<!DOCTYPE html>
<html>
<head>
<title>node-tests</title>
<script type="text/javascript" src="http://localhost:8001/socket.io/socket.io.js"> </script>
<script type="text/javascript">
var socket = io.connect('http://localhost', { port: 8001 });
socket.on('connect', function () {
alert('connect');
});
socket.on('error', function (data) {
console.log(data || 'error');
});
socket.on('connect_failed', function (data) {
console.log(data || 'connect_failed');
});
</script>
</head>
<body>
</body>
</html>
使用node server.js 启动我的服务器后,标准(预期)输出将写入服务器控制台:
info: socket.io started
当我在浏览器中打开 index.html(我的情况是 chrome - 未在其他浏览器上测试)时,以下日志将写入服务器控制台:
info: socket.io started
debug: served static content /socket.io.js
debug: client authorized
info: handshake authorized 9952353481638352052
debug: setting request GET /socket.io/1/websocket/9952353481638352052
debug: set heartbeat interval for client 9952353481638352052
debug: client authorized for
got a new connection from: 9952353481638352052
debug: setting request GET /socket.io/1/xhr-polling/9952353481638352052?t=1333635235315
debug: setting poll timeout
debug: discarding transport
debug: cleared heartbeat interval for client 9952353481638352052
debug: setting request GET /socket.io/1/jsonp-polling/9952353481638352052?t=1333635238316&i=0
debug: setting poll timeout
debug: discarding transport
debug: clearing poll timeout
debug: clearing poll timeout
debug: jsonppolling writing io.j[0]("8::");
debug: set close timeout for client 9952353481638352052
debug: jsonppolling closed due to exceeded duration
debug: setting request GET /socket.io/1/jsonp-polling/9952353481638352052?t=1333635258339&i=0
...
...
...
在浏览器控制台中我得到:
connect_failed
所以看起来客户端正在到达服务器并尝试连接,并且服务器正在授权握手,但客户端中从未触发 connect 事件,而是连接方法到达其 connect timeout 和 @987654332 @并放弃返回connect_failed。
对此的任何帮助\见解都会有所帮助。
谢谢
【问题讨论】:
-
尝试仅使用 io.connect() 它可以从您所在的 url 推断 URL 和端口。过去我遇到过问题,io.connect 中的东西没有像我期望的那样工作。
-
@kfiroo 你有解决办法吗?
-
@TimothyStrimple 谢谢蒂姆! 再次在 heroku (Cedar) 和 localhost 上工作!
标签: javascript node.js socket.io