因此,我正在尝试设置一个 socket.io 东西,用于在我的网站页面上来回中继聊天和其他消息,但我无法启动和运行它。发生的情况是,我启动我的服务器,然后打开客户端页面,服务器看到有人正在尝试连接并说了一堆东西。从客户端的角度来看,它尝试与 websockets 连接,然后超时,然后是 xhr-polling,它也超时,然后是 jsonp-polling,它也超时,然后连接失败。有时它会在连接一秒钟后断开,但这并不理想。我正在尝试与 chrome 连接,并设置了另一个可以工作的 websocket 服务器,所以我知道 websockets 至少是可能的,但跨浏览器的兼容性不足以满足我的需要,因此使用了 socket.io。
服务器.js
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.emit('connect_event', { hello: 'world' });
socket.on('message', function (msg) { socket.emit('message', msg);});
socket.on('disconnect', function () { });
});
客户端.php
<script src="http://domain.com:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('domain.com',{port: 8080});
socket.on('connecting', function (e) {console.log("attempting to connect with: "+e)});
socket.on('disconnect', function (e) {console.log(e)});
socket.on('connect_failed', function () {console.log("Connect Failed")});
socket.on('error', function (e) {console.log(e)});
socket.on('message', function (e) {console.log(e)});
socket.on('reconnect_failed', function (e) {console.log(e)});
socket.on('reconnect', function (e) {console.log(e)});
socket.on('reconnecting', function (e) {console.log(e)});
socket.on('connect', function () {
socket.send('hi');
console.log('connected');
});
socket.on('message', function (msg) {
console.log(msg);
});
</script>
浏览器中的 JS 控制台输出:
attempting to connect with: websocket client.php:5
attempting to connect with: xhr-polling client.php:5
attempting to connect with: jsonp-polling client.php:5
Connect Failed client.php:7
服务器调试信息:
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized yJKfSwjarsZxert_Ij5V
debug - setting request GET /socket.io/1/websocket/yJKfSwjarsZxert_Ij5V
debug - set heartbeat interval for client yJKfSwjarsZxert_Ij5V
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"connect_event","args":[{"hello":"world"}]}
debug - setting request GET /socket.io/1/xhr-polling/yJKfSwjarsZxert_Ij5V?t=1368452739259
debug - setting poll timeout
debug - discarding transport
debug - cleared heartbeat interval for client yJKfSwjarsZxert_Ij5V
debug - setting request GET /socket.io/1/jsonp-polling/yJKfSwjarsZxert_Ij5V?t=1368452749248&i=0
debug - setting poll timeout
debug - discarding transport
debug - clearing poll timeout
当服务器运行时,我可以去 domain.com:8080 它说
Welcome to socket.io.
因此,该端口也在 netstat -tan 中打开,用于确认目的:
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
error.log 中没有添加任何内容,只有页面的 get 请求被添加到访问日志中。
Socket.io 版本 0.9.14
node.js v 0.10.5 建议尝试不同的节点版本(特别是 0.8.x),但它们的行为似乎都相同。
服务器是带有 Ubuntu 12.04 LTS 的 VPS