使用 SSL 运行 socket.io



我正在使用socket.ionode.js超过express,我正在尝试通过SSL/https运行我的套接字

没有https一切都很好,但是当我尝试使用https运行它时,我无法让它工作。

这是我在编写node app.js和运行套接字时使用的app.js文件

Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
// This is the main file of our chat app. It initializes a new 
// express.js instance, requires the config and routes files
// and listens on a port. Start the application by running
// 'node app.js' in your terminal
var total = 0;
var usuarios = [];
var soporte = [];
var express = require('express'),
app = express();
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
// This is needed if the app is run on heroku:
var port = process.env.PORT || 8000;
// Initialize a new socket.io object. It is bound to 
// the express app, which allows them to coexist.
var io = require('socket.io').listen(app.listen(port));
io.on('connection', function(socket) {
socket.emit('supports',soporte.length);
socket.on('load_s',function(data){
//seguridad.push( socket );
soporte.push({'socket':socket,'id':socket.id});
usuarios.forEach(function(item, index, arr){
console.log(item)
if(item.atendido == false){
//socket.emit('lista',{'usuarios':usuarios});
}
});
console.log("Nuevo soporte conectado");
});
socket.on('get_supp',function(data){
});
socket.on('load_u',function(data){
var _s = socket;
usuarios[_s.id] = {'socket' : socket, 'atendido' : false}
console.log("Usuario en espera"+socket.id);
//////// Buscar Soporte y asignar /////
console.log("Soporte disponible "+ soporte.length);
if(soporte.length == 0){
console.log("No hay soporte disponible")
socket.emit('no_supp');
}else{
/// PONER EN LISTA PARA SOPORTE
socket.emit('wait');
/// ENVIAR NOTIFICACION A SOPORTES
for (i = 0; i < soporte.length; i++) {
soporte[i].socket.emit("nuevo_usuario", {'nombre':data.nombre, 'email':data.email, 'id':_s.id, 'question':data.question,'area': data.area})
}
}
});
socket.on('new_msg',function(data){
/// get usuario from list
var usuario = usuarios[data.id].socket
usuario.emit('new_msg', {'mensaje':data.mensaje,'nombre':data.nombre}); // enviar a usuario
});
socket.on('desconectar',function(data){
var usuario = usuarios[data.id].socket
usuario.emit('desconectar');
});
socket.on('new_msg_u',function(data){
/// get usuario from list
_id = socket.id;
for ( i = 0; i < soporte.length; i++){
if(soporte[i].id == data.id){
soporte[i].socket.emit('new_msg', {'mensaje':data.mensaje,'id_usuario':_id}); // enviar a usuario
}
}
});
socket.on('take_user',function(data){
/// tomar usuario ////
console.log("usuario tomado");
var id_soporte = socket.id // id de soporte
var id_usuario = data.id // id del usuario
usuarios[id_usuario].atendido = true // pasar atendido a verdadero
for (i = 0; i < soporte.length; i++) { /// emitir usuario tomado
if(soporte[i].id != socket.id){
soporte[i].socket.emit("usuario_tomado", {'id':id_usuario})
/// eliminar de la lista
}
}
usuarios[id_usuario].socket.emit('atendido',{'id_soporte':socket.id});
});
socket.on('send_chat',function(data){
if (data.id in departamentos) {
// send chat , esta conectado   
console.log('conectado');
usuarios[data.id].emit("mensaje",{text:data.text});
}
else{
// send push, está desconectado 
console.log('desconectado');
}
});
socket.on('send_chat_u',function(data){
if (data.id in soporte) {
// send chat , esta conectado   
console.log('conectado');
soporte[data.id].emit("mensaje",{text:data.text});
}
else{
// send push, está desconectado 
console.log('desconectado');
}
});
socket.on('disconnect', function() {
console.log("desconectado");
soporte.forEach(function(item, index, arr){
console.log(item.id+" .. "+socket.id+" ... "+index);
if(item.id == socket.id){
console.log("coincide");
delete soporte[index];
soporte.splice(index, 1);
}else{
item.socket.emit('usuario_desconectado',socket.id);
}
});
delete usuarios[socket.id];
});
});
console.log('Chat running' + port);

然后在我的 js 客户端文件中,我初始化我的聊天:

socket = io.connect('https://www.xxxxxxxxx.com.mx:8000', {secure: true});

我正在阅读此文档:

https://www.sitepoint.com/how-to-use-ssltls-with-node-js/

但是我不知道如何在express中实现它(我的代码示例在没有ssl的情况下可以正常运行(

我已经准备好使用privkey.pemcert.pem,但正如我之前所说,我不知道如何实现它。

谢谢。

好吧,我终于可以工作了。

socket = io.connect('https://www.xxxxx.com.mx:8000', {transports: ['websocket']});

这是我app.js代码:

var port = process.env.PORT || 8000;
// Initialize a new socket.io object. It is bound to 
// the express app, which allows them to coexist.

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
key: fs.readFileSync('/etc/letsencrypt/live/www.xxxxx.com.mx/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/www.xxxxx.com.mx/cert.pem'),
//ca: fs.readFileSync('./test_ca.crt'),
requestCert: false,
rejectUnauthorized: false
},app);
server.listen(8000);
var io = require('socket.io').listen(server);
io.on('connection', function(socket) {
...

最新更新