我需要能够在应用程序级别上平衡websocket。让我们根据我收到的消息说出前向websocket请求,在代理上解码它然后使用某些逻辑将该数据发送到另一个套接字服务器。
但我无法做到这一点。这是我编写的初始代码并尝试这样做。这是服务器
var http = require('http');
var httpProxy = require('http-proxy');
var WebSocket = require('ws');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
var proxy = httpProxy.createServer({target: 'ws://localhost:8080', ws:true});
var server = httpProxy.createServer(function(req, res) {
//SOME LOGIC HERE TO PARSE WS DATA AND SEND TO WS SERVER
proxy.ws(req, res, { target: 'ws://localhost:8080'});
}).listen(8014);
客户端
var http = require('http');
var httpProxy = require('http-proxy');
var WebSocket = require('ws');
var ws = new WebSocket('ws://localhost:8014/');
ws.on('open', function () {
ws.send("CLIENT");
});
ws.on('message', function (msg) {
console.log(msg);
});
答案 0 :(得分:3)
这是一个例子。在这种情况下,客户端直接连接到outer.js,然后将连接转发到上游服务器(inner.js)。
<强> outer.js 强>
var http = require('http');
var httpProxy = require('http-proxy');
var proxies = {
foo: new httpProxy.createProxyServer({
target: {
host: "foo.com",
port: 8080
}
}),
bar: new httpProxy.createProxyServer({
target: {
host: "bar.com",
port: 8080
}
})
// extend this...
};
var findUpstream = function(req){
// TODO return key for lookup in @proxies
};
var proxyServer = http.createServer(function (req, res){
var upstream = findUpstream(req);
proxies[upstream].web(req, res);
});
proxyServer.on('upgrade', function (req, socket, head) {
var upstream = findUpstream(req);
proxies[upstream].ws(req, socket, head);
});
proxyServer.listen(8014);
<强> inner.js 强>
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
在此示例中,您需要填写findUpstream
以根据请求中的数据返回foo
或bar
等密钥。如果没有找到合适的上游服务器,也值得进行一些错误处理,但这应该说明一般的想法。