使用 node.js 中的 socket.io 设置服务器-服务器 SSL 通信 [英] Setup Server-Server SSL communication using socket.io in node.js

查看:34
本文介绍了使用 node.js 中的 socket.io 设置服务器-服务器 SSL 通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 ssl 连接使用 socket.io 设置服务器到服务器的链接.这是我的例子:

I'm trying to setup a server to server link using socket.io over ssl connection. This is my example:

/**
 * Server
 */


var app = require('express')();
var config = require('./config');
var https = require('https');
var http = require('http');
var fs = require('fs');
var server = https.createServer({key: fs.readFileSync(config.ssl.key), cert: fs.readFileSync(config.ssl.cert), passphrase: config.ssl.passphrase}, app);
//var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.listen(config.port);

app.get('/', function (req, res) {
    res.send('Server');
  //res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});



/**
 * Client
 */


var io = require('socket.io-client');
//var socket = io.connect('http://localhost', {port: 8088});
var socket = io.connect('https://localhost', {secure: true, port: 8088});
  socket.on('connect', function(){
    socket.on('event', function(data){});
    socket.on('disconnect', function(){});
  });

代码在没有 SSL 的情况下运行正常.我怀疑可能是我的自签名证书没有被接受,但我不知道如何让客户端接受它.

The code works fine when ran without SSL. I suspect it could be my self-signed certificate not being accepted, but I do not know how to make the client accept it.

我可以接受自签名 SSL 证书吗,或者我可以采取其他方法吗?

Can I accept a self-signed SSL certificate, or is there another approach I can take?

推荐答案

经过多番搜索,在客户端中添加这个就可以了:

After some more searching, adding this in the client makes it work:

require('https').globalAgent.options.rejectUnauthorized = false;

require('https').globalAgent.options.rejectUnauthorized = false;

/**
 * Client
 */


var io = require('socket.io-client');
//var socket = io.connect('http://localhost', {port: 8088});

require('https').globalAgent.options.rejectUnauthorized = false; 

var socket = io.connect('https://localhost', {secure: true, port: 8088});
  socket.on('connect', function(){
    socket.on('event', function(data){});
    socket.on('disconnect', function(){});
  });

这篇关于使用 node.js 中的 socket.io 设置服务器-服务器 SSL 通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆