使用Redis在https上的Socketio

时间:2018-09-21 09:06:29

标签: node.js ssl redis socket.io lets-encrypt

我在bitnami灯架上有一个Web应用程序,操作系统是ubuntu,它使用Apache作为Web服务器。 SSL证书是使用“让我们加密”生成的。我可以通过http和https访问该网站。

Furthermore I am using following stacks:
 - nodejs
 - socket.io
 - redis

在本地计算机上发送通知可以正常工作,Websocket可以正常工作。

但是在运行于https的生产服务器上,它无法工作。我不断收到以下错误消息:

  

socket.io.js:2 GET https://mypage.com:3000/socket.io/?EIO=3&transport=polling&t=MNxGNEt   净:: ERR_CONNECTION_TIMED_OUT

这是我的socket.js(服务器)的样子:

var app   = require('http').createServer(handler);
var fs    = require('fs');
var io    = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();

// class declaration
var Redis = require('ioredis');

function handler(req, res) {
    res.writeHead(200);
    res.end('');
}

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

var redisUserSignedUp = new Redis();

redisUserSignedUp.subscribe('signed-up-channel');

redisUserSignedUp.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

// run server on port 3000
app.listen(3000, function () {
    console.log('Server runs!');
});

在我的作品中,我目前正在这样尝试:

var app = require('https').createServer({
    key: fs.readFileSync('/opt/bitnami/apache2/conf/serverKey.pem'),
    cert: fs.readFileSync('/opt/bitnami/apache2/conf/serverCrt.pem')
 }, handler);
var fs    = require('fs');
var io    = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();

// class declaration
var Redis = require('ioredis');

function handler(req, res) {
    res.writeHead(200);
    res.end('');
}

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

var redisUserSignedUp = new Redis();

redisUserSignedUp.subscribe('signed-up-channel');

redisUserSignedUp.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

// run server on port 3000
app.listen(3000, function () {
    console.log('Server runs!');
});

我正在尝试像这样访问它:

var options = {
    key: fs.readFileSync('/opt/bitnami/apache2/conf/serverKey.pem'),
    cert: fs.readFileSync('/opt/bitnami/apache2/conf/serverCrt.pem'),
    requestCert: true    
}

var app   = require('https').createServer(options, handler);

本地:

const socket = io('http://myapp.test:3000'); // localhost dev Folder is mapped to this .test url
socket.on('signed-in-channel:App\\Events\\UserSignedIn', (data) => {
   …

生产:

var socket = io('mypage.com:3000', {secure: true});

1 个答案:

答案 0 :(得分:0)

您仅创建一个http服务器,但是要与ssl连接,您需要一个https服务器。

var options = {
    key: fs.readFileSync('./file.pem'),
    cert: fs.readFileSync('./file.crt')
};

var app = require('https').createServer(handler);