Created
February 6, 2025 20:01
-
-
Save adamgajzlerowicz/f30f0a8a06da86cab6296fa49874c469 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http') | |
const express = require('express') | |
const WebSocket = require('ws') | |
const app = express() | |
const server = http.createServer(app) | |
const wss = new WebSocket.Server({ server }) | |
const deviceUrl = 'ws://192.168.1.99/timerws' | |
const deviceSocket = new WebSocket(deviceUrl) | |
const browserClients = new Set() | |
deviceSocket.on('message', msg => { | |
for (const client of browserClients) { | |
if (client.readyState === WebSocket.OPEN) { | |
client.send(msg) | |
} | |
} | |
}) | |
wss.on('connection', browserSocket => { | |
console.log('Connection connected') | |
browserClients.add(browserSocket) | |
browserSocket.on('message', msg => { | |
if (deviceSocket.readyState === WebSocket.OPEN) { | |
deviceSocket.send(msg) | |
} | |
}) | |
browserSocket.on('close', () => { | |
browserClients.delete(browserSocket) | |
if (!browserClients.size && deviceSocket.readyState === WebSocket.OPEN) { | |
deviceSocket.close() | |
} | |
}) | |
}) | |
server.listen(4326, () => console.log('Proxy server on port 4326')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment