使用socket.io与HTTPS而不是HTTP

时间:2015-02-01 17:44:28

标签: sockets ssl socket.io

我使用自签名证书来加密流量数据。 我的 .crt .key 文件位于 / etc / nginx / ssl /

some_file.key some_file.crt

我正在使用socket.io而不是http,但试图将其转换为https。这是我的实际代码:

var formidable = require('formidable');
var express = require('express');
var fs = require('fs');

var privateKey = fs.readFileSync('../etc/nginx/ssl/some_file.key').toString();
var certificate = fs.readFileSync('../etc/nginx/ssl/some_file.crt').toString();

//how can I exclude this? (I have no intermediate, should I?)
var ca = fs.readFileSync('../intermediate.crt').toString();

var app = express.createServer({key:privateKey,cert:certificate,ca:ca });
var io = require('socket.io');

app.listen(3000, function(){
    //wait on 3000
});

app.post('/posts', function(req, res){
    //server communication
});

io.on('connection', function(socket){
    //wait on connections
});

客户端:

var socket = io(url + ":3000", { "secure": true, 'connect timeout': 5000 });

这是正确的方法吗?我的https代码基于示例,所以我怀疑这是否足够好(我知道它不是,但应该很接近)。当我运行代码时,我也收到错误no such file or directory '../etc/nginx/ssl/some_file.key' ...

1 个答案:

答案 0 :(得分:0)

我以这种方式使用它,虽然这非常依赖于您使用的快速版本。这适用于版本3.4

var express = require('express')
, app = express()
,fs = require('fs')
,events = require('events');
...
var options = {
    key:    fs.readFileSync('/etc/nginx/ssl/some_file.key'),
    cert:   fs.readFileSync('/etc/nginx/ssl/some_file.crt')
};

/*
*Configuration
*
*/
var server = require('https').createServer(options, app), io = require("socket.io").listen(server);
var port = 8443;
var ipaddr = '0.0.0.0';

app.configure(function() {
    app.set('port', port);
    app.set('ipaddr', ipaddr);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    ...
});