Snippets

Tharo Fideley Websocket to tcp Proxy

Created by Tharo Fideley
/** 
 *  Ever had the Issue that you would like to connecto with javascript to
 *  something that needs 'real' ports? Well then u might know the trouble
 *  with finding an working an easy to use code about this.
 *
 *  This are the few lines I tend to use. Is reather an example then solid
 *  code since it lacks of encoding, binary mode and error handling.
 *
 *  But it works just like a charme without messing around with tousands of
 *  libs and classes and everything. 
**/

const WebSocket = require('ws');
const net = require('net');
const wss = new WebSocket.Server({ port: 8080 });
const querystring = require('querystring');
const URL = require('url');

const whitelist = {
  '/echo' : { server:'127.0.0.1', port:1337 },
};


/** not rlly necessary switch to enable 'different targets' functionality **/
var getConfig = function(ws) {
  let refurl = URL.parse(ws.upgradeReq.url);

  // try to find config on whitelist
  let conf = whitelist[refurl.pathname];
  if(!conf || !conf.server || !conf.port) {
    return false;
  }
  else {
    conf = Object.assign({}, conf);
  }

  // try to find paramerers
  let params = {};
  if(ws.upgradeReq.method==='GET') {
    var p = ws.upgradeReq.url.replace(refurl.pathname, '');
    if(p[0]==='?') {
      params = querystring.parse(p.substr(1));
      // merge with config?
      if(!conf.fixed)
        conf = Object.assign(params, conf);
    }
  }

  if(!conf.encoding)
    conf.encoding = 'text';

  return conf;
}


wss.on('connection', function connection(ws) {
  var conf = getConfig(ws);

  if(conf===false) {
    ws.close(1002, 'Unknown Route.');
    return;
  }

  var tcp = new net.Socket();
  tcp.connect(conf.port, conf.server, function() {
    //ws.send('connection etablished');
  });

  // msg events
  ws.on('message', (message) => {
    if(conf.encoding==='text')
      tcp.write(message);
    //TODO: bin connection!
  });
  tcp.on('data', (data) => {
    if(conf.encoding==='text')
      ws.send( data.toString() );
    //TODO: bin connection
  });

  // error events
  ws.on('error', (err) => {
    console.log('WS_ERROR: ', err);
    tcp.end();
  });
  tcp.on('error', (err) => {
    console.log('SOCKET_ERROR: ', err);
    ws.close(1011, JSON.stringify(err));
  });

  // disconnect events
  ws.on('close', () => { tcp.end();  });
  tcp.on('close',() => { ws.close(1000); });  // aka on('end', ...
});

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.