我想查看网络套接字连接的第一个数据包的标头,然后从那里决定如何处理它。
TCP 示例(有效,但无用)
这是没用的,因为它不能解决我的问题,它只是证明,理论上,问题是可以解决的。
'use strict';
var net = require('net');
var http = require('http');
var http80 = http.createServer(function (req, res) {
res.end('Hello, World!');
});
var tcp80 = net.createServer(function (socket) {
socket.once('data', function (chunk) {
if (/http\/1/i.test(chunk.toString())) {
console.log("looks like http, continue");
http80.emit('connection', socket);
} else {
console.log("looks like tcp, die");
socket.end();
}
socket.pause();
process.nextTick(function () {
socket.emit('data', chunk);
socket.resume();
});
});
});
tcp80.listen(80, function () {
console.log('listening on 80');
});
TLS 示例(不起作用)
这是我实际上正在尝试做的,但不起作用:
'use strict';
var net = require('net');
var sni = require('sni');
var https = require('https');
var tlsOpts = require('localhost.daplie.com-certificates').merge({});
var https443 = https.createServer(tlsOpts, function (req, res) {
res.end('Hello, Encrypted World!');
});
var tcp443 = net.createServer(function (socket) {
// looking at the first packet, this is the gold
socket.once('data', function (chunk) {
// undo the read, more or less
socket.pause();
process.nextTick(function () {
socket.emit('data', chunk);
socket.resume();
});
if (/^tcp\.example\.com/i.test(sni(chunk))) {
console.log("TODO: handle as raw tls / tcp");
return;
}
console.log("handling as https");
https443.emit('connection', socket);
});
});
tcp443.listen(443, function () {
console.log('listening on 443');
});
我尝试过手动发出readable
事件以及data
使用块和resume
ing 手动发出事件,但它似乎在所有这些情况下都挂起,而不是像上面的示例那样工作。