node.js - 如何使用套接字将请求代理到 h2c HTTP/2 服务器?

标签 node.js http2

这一定是一个简单的问题,但我对流的了解有限。

HTTP/1 80 到 HTTP/2 h2c 代理

脚本(不起作用):

const net = require('net');
const http = require('http');
const http2 = require('http2');
const socketPath = `/tmp/socket.test.${Date.now()}`;

// front http 80 server.
http.createServer((req, res) => {
    const socket = net.createConnection(socketPath)
    req.pipe(socket).pipe(res);
}).listen(80);

// private http2 socket server.
http2.createServer(function(socket) {
    socket.write(`Echo from http2 server\r\n`);
    socket.pipe(socket);
}).listen(socketPath);

HTTP/2 h2c 到 HTTP/2 h2c 代理

cli 命令启动请求:

curl --http2-prior-knowledge -v http://localhost:3333/ --output -

脚本(不起作用):

const net = require('net');
const http = require('http');
const http2 = require('http2');
const socketPath = `/tmp/socket.test.${Date.now()}`;
const port = 3333;

const private = http2.createServer({allowHTTP1: true});
private.on('stream', (stream, headers) => {
    console.log('private http2 request');
    stream.end('HTTP/2');
});
private.listen(socketPath, () => console.log('private http2 server is listening', socketPath));

const public = http2.createServer({allowHTTP1: true});
public.on('stream', (stream, headers) => {
    console.log('public http2 request');
    const socket = net.connect(socketPath);
    stream.pipe(socket).pipe(stream);
});
public.listen(port, () => console.log('public http2 server is listening port', port));

最佳答案

最后,http2(h2c) 到 http2(h2c)(使用 unix 套接字)代理工作了!

const net = require('net');
const http2 = require('http2');
const socketPath = `/tmp/socket.test.${Date.now()}`;
const port = 4444;

const priv = http2.createServer({});
priv.on('stream', (stream, headers) => {
    console.log('private http2 request');
    stream.end('HTTP/2');
});
priv.listen(socketPath, () => console.log('private http2 server is listening', socketPath));

const pub = http2.createServer({});
pub.on('stream', (stream, headers) => {
    const clientSession = http2.connect('http://0.0.0.0', {
        createConnection: () => net.connect({path: socketPath})
    });
    const req = clientSession.request({
      ':path': `/`,
    });
    req.pipe(stream).pipe(req);
});
pub.listen(port, () => console.log('public http2 server is listening port', port));

关于node.js - 如何使用套接字将请求代理到 h2c HTTP/2 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181463/

相关文章:

node.js - http/2 推送的 javascript 未加载

c++ - 从带有非 ASCII 字符的 wchar_t 创建 v8::String 的安全方法是什么?

json - Node.js/Express/Mongoose - 如何发送 JSON 和对象 View ?

javascript - 处理来自控制台的nodeJs输入?

javascript - 伪 MEAN 应用程序 - Angular 2 Node Api

websocket - 用于双向消息流的 HTTP/2 与 web-sockets

node.js - 无法安装 waterlock 本地身份验证

jetty - 使用 maven-jetty-plugin 启用 HTTP2

websocket - HTTP/2 或 Websockets 用于低延迟客户端到服务器消息

http - HTTP2 草案中使用的缩写词