这是可能的,但首先您需要了解 node.js 的工作原理:
不幸的是,HTTP 服务器硬连线到 TCP 服务器(参见源代码):
function Server(requestListener) {
if (!(this instanceof Server)) return new Server(requestListener);
net.Server.call(this, { allowHalfOpen: true });
...
this.addListener('connection', connectionListener);
...
}
您需要将您的套接字传递给 http.js 中定义的 connectionListener。好消息是模块导出它:
exports._connectionListener = connectionListener;
我还没有尝试过这段代码,但它应该可以进行一些调整:
var util = require('util'),
events = require('events'),
http = require('http'),
express = require('express'),
app = express();
function FakeServer() {
events.EventEmitter.call(this);
this.on('connection', http._connectionListener);
this.on('request', app);
}
util.inherits(FakeServer, events.EventEmitter);
var server = new FakeServer();
process.on('message', function ('socket', socket) {
server.emit('connection', socket);
});
// you can use app as a regular express app
app.get('/hello', function (req, res) {
res.send('world');
};