我正在开发一个网页应用,并且正在加入websocket连接。我已经使用node.js(5.0.0)和websocket(https://www.npmjs.com/package/websocket)安装了一个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 */
};