httpolyglot, 通过 node.js 在同一端口上提供http和https连接

分享于 

3分钟阅读

GitHub

  繁體 雙語
Serve http and https connections over the same port with node.js
  • 源代码名称:httpolyglot
  • 源代码网址:http://www.github.com/mscdex/httpolyglot
  • httpolyglot源代码文档
  • httpolyglot源代码下载
  • Git URL:
    git://www.github.com/mscdex/httpolyglot.git
    Git Clone代码到本地:
    git clone http://www.github.com/mscdex/httpolyglot
    Subversion代码到本地:
    $ svn co --depth empty http://www.github.com/mscdex/httpolyglot
    Checked out revision 1.
    $ cd repo
    $ svn up trunk
    
    描述

    用于在同一端口上提供http和https连接的模块。

    要求
    • node.js -- v0.10.0或者更高版本
    安装
    
    npm install httpolyglot
    
    
    
    
    示例
    • 简单用法:
    var httpolyglot =require('httpolyglot');var fs =require('fs');httpolyglot.createServer({
     key:fs.readFileSync('server.key'),
     cert:fs.readFileSync('server.crt')
    }, function(req, res) {
     res.writeHead(200, { 'Content-Type':'text/plain' });
     res.end((req.socket.encrypted?'HTTPS':'HTTP') +' Connection!');
    }).listen(9000, 'localhost', function() {
     console.log('httpolyglot server listening on port 9000');
     // visit http://localhost:9000 and https://localhost:9000 in your browser.. .});
    • 简单重定向到https的所有http连接:
    var httpolyglot =require('httpolyglot');var fs =require('fs');httpolyglot.createServer({
     key:fs.readFileSync('server.key'),
     cert:fs.readFileSync('server.crt')
    }, function(req, res) {
     if (!req.socket.encrypted) {
     res.writeHead(301, { 'Location':'https://localhost:9000' });
     returnres.end();
     }
     res.writeHead(200, { 'Content-Type':'text/plain' });
     res.end('Welcome, HTTPS user!');
    }).listen(9000, 'localhost', function() {
     console.log('httpolyglot server listening on port 9000');
     // visit http://localhost:9000 and https://localhost:9000 in your browser.. .});
    API

    导出

    • 服务器 - 一个类似 https.Server (。除了实例有来自 http。Server的setTimeout() )的类。

    • createServer (。<对象> tlsConfig [, <function> requestListener] ) 服务器创建并返回一个新的服务器实例。

    工作原理

    TLS和HTTP连接很容易区分,因为客户端发送的第一个字节试图连接。 有关更多信息,请参见本评论。


    相关文章