我正在开发一个网络应用程序,并包括websocket连接。我已经安装了一个websocket服务器,带有node.js(5.0.0)和websocket(https://www.npmjs.com/package/websocket)。
在Chrome中,它运行得很好,但在Firefox中,这条消息出现在控制台中:
Firefox no puede establecer una conexión con el servidor en wss://www.my-dev-server.com:1337/.
(Firefox无法与位于的服务器建立连接…)
这是服务器代码(基本上与示例相同):
var WebSocketServer = require('websocket').server;
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('/keyfile.key'),
cert: fs.readFileSync('/pemfile.pem')
};
var port = 1337;
// Create HTTPS service.
var server = https.createServer(options, function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(port, function() {
console.log((new Date()) + ' Server is listening on port ' + port);
});
// create the server
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed( origin ) {
// TODO: complete
return true;
}
var clients = [];
// WebSocket server
wsServer.on('request', function(request) {
if( !originIsAllowed( request.origin ) ) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + 'rejected.');
return;
}
console.log((new Date()) + ' Connection accepted from ' + request.origin + '.');
var connection = request.accept(null, request.origin);
clients.push(connection);
connection.on('message', function( message ) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
}
else if( message.type === 'binary' ) {
}
});
connection.on( 'error', function( error ) {
});
connection.on('close', function( reasonCode, description ) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
});
我使用自签名证书进行开发,与web服务器使用的证书相同。
这是我的客户代码:
var connection = new WebSocket('wss://www.my-dev-server.com:1337');
connection.onopen = function () { };
connection.onerror = function (error) { };
connection.onmessage = function (message) {
/* some code here */
};
我终于找到了解决方案。
问题是,对于https连接,在端口443中,Firefox已经为未知证书存储了一个异常,而它需要为wss存储另一个异常(在本例中为端口1337)。
我在高级首选项中为该端口添加了一个证书异常,现在运行良好。