From 97d38dd4ee9ae37c3c307f601dfee0f8b3b6437f Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Sat, 18 Mar 2017 22:33:00 +0100 Subject: Add websocket translation script --- websockets/.gitignore | 1 + websockets/package.json | 22 ++++++++++++++++++++++ websockets/server.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 websockets/.gitignore create mode 100644 websockets/package.json create mode 100755 websockets/server.js (limited to 'websockets') diff --git a/websockets/.gitignore b/websockets/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/websockets/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/websockets/package.json b/websockets/package.json new file mode 100644 index 0000000..7a71e7d --- /dev/null +++ b/websockets/package.json @@ -0,0 +1,22 @@ +{ + "name": "tomsg-webserver", + "version": "0.1.0", + "description": "tomsg websocket-to-tcp converter", + "main": "server.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://git.tomsmeding.com/tomsg" + }, + "keywords": [ + "tomsg", + "webserver" + ], + "author": "Tom Smeding (https://tomsmeding.com)", + "license": "MIT", + "dependencies": { + "ws": "^2.2.1" + } +} diff --git a/websockets/server.js b/websockets/server.js new file mode 100755 index 0000000..c6af67f --- /dev/null +++ b/websockets/server.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +const net=require("net"); +const WebSocket=require("ws"); + +const PORT=29546; + +const upstream={ + host: "localhost", + port: 29536 +}; + + +const server=new WebSocket.Server({port:PORT},()=>{ + console.log(`Listening for websocket http requests on port ${PORT}`); +}); +server.on("connection",(sock)=>{ + let netconn=null; + let buffer=[]; + + netconn=net.connect(upstream.port,upstream.host,()=>{ + for(const item of buffer){ + netconn.write(item); + } + buffer=[]; + }); + netconn.on("close",()=>{ + sock.close(); + }); + netconn.on("data",(data)=>{ + sock.send(data); + }); + + sock.on("close",()=>{ + netconn.end(); + }); + sock.on("message",(data)=>{ + if(netconn.connecting)buffer.push(data); + else netconn.write(data); + }); +}); + +process.on("SIGINT",()=>{ + console.log("Closing websocket server..."); + server.close(); +}); -- cgit v1.2.3-70-g09d2