anyproxy/lib/wsServerMgr.ts

48 lines
1.0 KiB
TypeScript
Raw Normal View History

2017-12-12 20:07:06 +08:00
/**
* manage the websocket server, for proxy target only
2017-12-12 20:07:06 +08:00
*
*/
import * as ws from 'ws';
import * as http from 'http';
import * as https from 'https';
import logUtil from './log.js';
2017-12-12 20:07:06 +08:00
const WsServer = ws.Server;
/**
* get a new websocket server based on the server
* @param @required {object} config
{string} config.server
{handler} config.handler
*/
function getWsServer(config: {
server: http.Server | https.Server;
connHandler: (wsClient: ws, wsReq: http.IncomingMessage) => void;
}): ws.Server {
2017-12-12 20:07:06 +08:00
const wss = new WsServer({
server: config.server,
2017-12-12 20:07:06 +08:00
});
wss.on('connection', config.connHandler);
wss.on('headers', (headers) => {
headers.push('x-anyproxy-websocket:true');
});
wss.on('error', (e) => {
2017-12-12 20:07:06 +08:00
logUtil.error(`error in websocket proxy: ${e.message},\r\n ${e.stack}`);
console.error('error happened in proxy websocket:', e);
2017-12-12 20:07:06 +08:00
});
wss.on('close', (e) => {
2017-12-12 20:07:06 +08:00
console.error('==> closing the ws server');
});
return wss;
}
export default {
getWsServer,
};