cnxkey

Nodejs搭建wss服务器

首先使用OpenSSL创建自签名证书:

复制代码
#生成私钥key文件
openssl genrsa 1024 > /path/to/private.pem
//
#通过私钥文件生成CSR证书签名
openssl req -new -key /path/to/private.pem -out csr.pem
//
#通过私钥文件和CSR证书签名生成证书文件
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/private.pem -out /path/to/file.crt
复制代码

使用ws模块创建wss服务器:

复制代码
var https=require(\'https\');
var ws=require(\'ws\');
var fs=require(\'fs\');
var keypath=process.cwd()+\'/server.key\';//我把秘钥文件放在运行命令的目录下测试
var certpath=process.cwd()+\'/server.crt\';//console.log(keypath);
//console.log(certpath);
 
var options = {
  key: fs.readFileSync(keypath),
  cert: fs.readFileSync(certpath),
  passphrase:\'1234\'//如果秘钥文件有密码的话,用这个属性设置密码
};
 
var server=https.createServer(options, function (req, res) {//要是单纯的https连接的话就会返回这个东西
    res.writeHead(403);//403即可
    res.end("This is a  WebSockets server!\n");
}).listen(15449);
 
 
var wss = new ws.Server( { server: server } );//把创建好的https服务器丢进websocket的创建函数里,ws会用这个服务器来创建wss服务
//同样,如果丢进去的是个http服务的话那么创建出来的还是无加密的ws服务
wss.on( \'connection\', function ( wsConnect ) {
    wsConnect.on( \'message\', function ( message ) {
        console.log( message );
    });
});
复制代码

客户端链接:

var ws = new WebSocket(\'wss://localhost:15449/\', {
  protocolVersion: 8,
  origin: \'https://localhost:15449\',
  rejectUnauthorized: false //重要,自签名证书只能这样设了。CA颁发的受信任证书就不需要了
});

 

分类:

技术点:

相关文章:

  • 2021-10-01
  • 2021-11-18
  • 2021-08-06
  • 2022-12-23
  • 2021-09-24
  • 2021-10-09
  • 2021-04-19
  • 2022-01-08
猜你喜欢
  • 2021-11-12
  • 2022-12-23
  • 2021-12-31
  • 2021-10-13
  • 2021-06-05
  • 2022-01-21
  • 2022-01-08
相关资源
相似解决方案