/** * 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. **/constWebSocket=require('ws');constnet=require('net');constwss=newWebSocket.Server({port:8080});constquerystring=require('querystring');constURL=require('url');constwhitelist={'/echo':{server:'127.0.0.1',port:1337},};/** not rlly necessary switch to enable 'different targets' functionality **/vargetConfig=function(ws){letrefurl=URL.parse(ws.upgradeReq.url);// try to find config on whitelistletconf=whitelist[refurl.pathname];if(!conf||!conf.server||!conf.port){returnfalse;}else{conf=Object.assign({},conf);}// try to find paramerersletparams={};if(ws.upgradeReq.method==='GET'){varp=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';returnconf;}wss.on('connection',functionconnection(ws){varconf=getConfig(ws);if(conf===false){ws.close(1002,'Unknown Route.');return;}vartcp=newnet.Socket();tcp.connect(conf.port,conf.server,function(){//ws.send('connection etablished');});// msg eventsws.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 eventsws.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 eventsws.on('close',()=>{tcp.end();});tcp.on('close',()=>{ws.close(1000);});// aka on('end', ...});
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.