【问题标题】:Using greenlock-express with web sockets将 greenlock-express 与 Web 套接字一起使用
【发布时间】:2018-06-23 23:11:20
【问题描述】:

寻找一个如何设置 HTTPS 与 greenlock-express 结合安全 websocket 服务器的示例。

【问题讨论】:

    标签: node.js https websocket node-modules greenlock


    【解决方案1】:

    这就是我最终设置它的方式。关键是使用 greenlock-express 生成的 tslOptions 手动设置一个 HTTPS 服务器,然后以正常方式附加一个 Websocket 服务器。使用这种方法,必须手动完成从 HTTP 到 HTTPS 的重定向。

    我最初无法正常工作,因为我没有打开服务器上的 443 端口。确保你这样做,否则 HTTPS 将无法工作!

    const express = require('express');
    const http = require('http');
    const https = require('https');
    const WebSocket = require('ws');
    
    //EXPRESS TO BUNDLE APP
    let my_app = express();
    let dir = __dirname + '/../app';
    io_app.use(express.static(dir));
    //Just serving static files from a sibling directory called /app
    
    //// SETUP HTTP GREENLOCK
    
    let greenlock = require('greenlock-express').create({
    
      // Let's Encrypt v2 is ACME draft 11
      version: 'draft-11'
    
        ,
      server: 'https://acme-v02.api.letsencrypt.org/directory'
        // Note: If at first you don't succeed, switch to staging to debug
        // https://acme-staging-v02.api.letsencrypt.org/directory
    
        // You MUST change this to a valid email address
        ,
      email: 'test@example.com'
    
        // You MUST NOT build clients that accept the ToS without asking the user
        ,
      agreeTos: true
    
        // You MUST change these to valid domains
        // NOTE: all domains will validated and listed on the certificate
        ,
      approveDomains: ['example.com', 'www.example.com']
    
        // You MUST have access to write to directory where certs are saved
        // ex: /home/foouser/acme/etc
        ,
      configDir: require('path').join(require('os').homedir(), 'acme', 'etc')
    
        // Join the community to get notified of important updates and help me make greenlock better
        ,
      communityMember: true
    
        // Contribute telemetry data to the project
        ,
      telemetry: true
    
        ,
      debug: true
    
    });
    
    //// REDIRECT HTTP TO HTTPS
    
    let redirectHttps = require('redirect-https')();
    let acmeChallengeHandler = greenlock.middleware(redirectHttps);
    http.createServer(acmeChallengeHandler).listen(80, function() {
      console.log("Listening for ACME http-01 challenges on", this.address());
    });
    
    //// HTTPS SERVER + WEBSOCKETS
    
    let server = https.createServer(greenlock.tlsOptions, my_app);
    
    let ws = new WebSocket.Server({
      server
    });
    
    ws.on('connection', function(ws, req) {
      //websocket on connection... 
    });
    
    server.listen(443);

    【讨论】:

    猜你喜欢
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    相关资源
    最近更新 更多