【发布时间】:2014-08-18 21:27:24
【问题描述】:
我有一个运行 socket.io 服务器的节点服务器和一个使用它的客户端。简单的故事,我需要能够在两者之间传递消息。这在支持 Web 套接字的浏览器中按预期工作,但是当需要使用后备方法时它不起作用。 我应该提到,页面是从 apache 服务器提供的,节点服务器仅用于特定页面。我正在使用的代码如下,我已经修改了一段时间,无法弄清楚如何修复它。
另外值得一提的是,在IE9中打开页面时(不支持websockets), 记录 connection.io.engine.transport.name 将给出“websocket”。
客户:
connection = io(window.location.protocol + '//localhost:8888', {
'reconnect': false,
'max reconnection attempts': 0,
'transports':
[
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
]
});
connection.on('connect',function () {
console.log("Socket is open");
$('#dc-status').hide();
connection.emit('message',JSON.stringify(info));
connection.on('message',function (e) {
//DO SOMETHING WITH THE DATA RECIEVED
});
});
服务器: var ioserver = require('socket.io');
var io = ioserver.listen(8888);
var http = require("http");
console.log("server started...");
io.set('transports',[
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
]);
io.sockets.on('connection', function(ws) {
var req;
var order;
var courier;
var after;
var session;
var options = {};
console.log("New client connected");
// console.log("Transport: " + io.transports[ws.id].name);
ws.on('message', function(data) {
//WORK WITH THE DATA RECEIVED
//NOT RELEVANT TO EXAMPLE
console.log('received: %s', data);
parsedData = JSON.parse(data);
});
ws.on('disconnect', function () {
console.log("Connection closed");
});
});
【问题讨论】:
-
Socket.io > 1.0 不再使用回退,而是使用升级方法。
Socket.IO never assumes that WebSocket will just work, because in practice there’s a good chance that it won’t. Instead, it establishes a connection with XHR or JSONP right away, and then attempts to upgrade the connection to WebSocket.. -
感谢您的回答。这是否意味着我需要重构服务器代码?因为当我在 IE9 中打开页面时,我什至没有得到“服务器已启动...”日志。
标签: javascript node.js websocket socket.io