mirror of
https://github.com/alibaba/anyproxy.git
synced 2025-08-04 21:39:04 +00:00
optimize webServer, move it to /lib
This commit is contained in:
88
lib/wsServer.js
Normal file
88
lib/wsServer.js
Normal file
@@ -0,0 +1,88 @@
|
||||
//websocket server manager
|
||||
|
||||
var WebSocketServer = require('ws').Server,
|
||||
logUtil = require("./log");
|
||||
|
||||
function resToMsg(msg,cb){
|
||||
var result = {},
|
||||
jsonData;
|
||||
|
||||
try{
|
||||
jsonData = JSON.parse(msg);
|
||||
}catch(e){
|
||||
result = {
|
||||
type : "error",
|
||||
error: "failed to parse your request : " + e.toString()
|
||||
};
|
||||
cb && cb(result);
|
||||
return;
|
||||
}
|
||||
|
||||
if(jsonData.reqRef){
|
||||
result.reqRef = jsonData.reqRef;
|
||||
}
|
||||
|
||||
if(jsonData.type == "reqBody" && jsonData.id){
|
||||
GLOBAL.recorder.getBodyUTF8(jsonData.id, function(err, data){
|
||||
if(err){
|
||||
result = {
|
||||
type : "body",
|
||||
content : {
|
||||
id : null,
|
||||
body : null,
|
||||
error : err.toString()
|
||||
}
|
||||
};
|
||||
}else{
|
||||
result = {
|
||||
type : "body",
|
||||
content : {
|
||||
id : jsonData.id,
|
||||
body : data
|
||||
}
|
||||
};
|
||||
}
|
||||
cb && cb(result);
|
||||
});
|
||||
}else{ // more req handler here
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//config.port
|
||||
function wsServer(config){
|
||||
//web socket interface
|
||||
var wss = new WebSocketServer({port: config.port});
|
||||
wss.broadcast = function(data) {
|
||||
if(typeof data == "object"){
|
||||
data = JSON.stringify(data);
|
||||
}
|
||||
|
||||
for(var i in this.clients){
|
||||
try{
|
||||
this.clients[i].send(data);
|
||||
}catch(e){
|
||||
logUtil.printLog("websocket failed to send data, " + e, logUtil.T_ERR);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
wss.on("connection",function(ws){
|
||||
ws.on("message",function(msg){
|
||||
resToMsg(msg,function(res){
|
||||
res && ws.send(JSON.stringify(res));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
GLOBAL.recorder.on("update",function(data){
|
||||
wss && wss.broadcast({
|
||||
type : "update",
|
||||
content: data
|
||||
});
|
||||
});
|
||||
|
||||
return wss;
|
||||
}
|
||||
|
||||
module.exports = wsServer;
|
||||
Reference in New Issue
Block a user