在node.js上使用websockets的Https服务器

时间:2017-09-12 11:37:10

标签: node.js websocket

我正在尝试创建支持websockets的简单https服务器。我有一些https服务器和websockets的功能代码,但都是独立的。不知道如何结合它。我更喜欢使用免费使用库(MIT,..)

我希望能够提供http请求和websockets。

Https示例升级,但不知道如何处理升级后的websocket连接,我的第二个例子就是这样。

connection. process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var https = require('https');
var websocket = require('websocket');
var fs = require('fs');

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

var server = https.createServer(
    options
  , function(req,res) {

    console.log('req');

    res.writeHeader(200, { 'Content-Type': 'text/plain' });
    res.write('test');
    res.end();
  }
);
server.on('upgrade', (req, socket, head) => {

    console.log('upgrade ');

  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
               'Upgrade: WebSocket\r\n' +
               'Connection: Upgrade\r\n' +
               '\r\n');

  socket.pipe(socket);
});

server.listen(8080, '127.0.0.1', () => {

  // make a request
  const options = {
    port: 8080,
    hostname: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };

  const req = https.request(options);
  req.end();

  req.on('upgrade', (res, socket, upgradeHead) => {

    console.log('got upgraded!');

*** so what to do here ***


    /*
    socket.end();
    process.exit(0);
    */
  });
});

这是功能性的websockets,但无法处理简单的http(s)请求。

var https = require('https');
var ws = require('websocket').server;
var fs = require('fs');

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


var server = https.createServer(
        options
, function(req,res) {
        res.writeHeader(200);
        res.end();
}
);

server.listen(8080);


var wss = new ws({httpServer:server});

var connectionNumber=0;
console.log('start ');
wss.on('request',function(req){

        req.on('requestAccepted',function(conn){

                conn.on('message',function(msg){

                        conn.send('test');
                });

                conn.on('close',function(msg){
                });

        });

        req.accept(null,req.origin);
});

我一直在寻找组合解决方案的功能示例,但没有任何运气。

2 个答案:

答案 0 :(得分:2)

您可以使用自签名证书(代码1006)来解决wss连接问题。在这种情况下,您必须将证书添加到根CA(FirefoxChrome)。

// app.js
'use strict'
const https = require('https');
const fs = require('fs');
const ws = require('ws');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

const index = fs.readFileSync('./index.html');

let server = https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end(index);
});
server.addListener('upgrade', (req, res, head) => console.log('UPGRADE:', req.url));
server.on('error', (err) => console.error(err));
server.listen(8000, () => console.log('Https running on port 8000'));

const wss = new ws.Server({server, path: '/echo'});
wss.on('connection', function connection(ws) {
    ws.send('Hello');   
    ws.on('message', (data) => ws.send('Receive: ' + data));
});
// index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
<script>
    var socket = new WebSocket('wss://127.0.0.1:8000/echo');
    socket.onopen = () => console.log('Connected') || setInterval(() => socket.send(new Date().toLocaleString()), 1000);    
    socket.onclose = (event) =>  console.log((event.wasClean) ? 'Disconnected' :  'Connection break: ' + (event.reason || event.code)); 
    socket.onmessage = (event) => console.log('DATA', event.data);
    socket.onerror = (err) => console.error(err.message);
</script>
Press F12 to open console...
</body>
</html>

答案 1 :(得分:0)

由于您使用的是Node,我建议您查看Socket.io。它比使用所有手动websocket连接逻辑更容易使用。