blob: d0b963bf682fb18e7d2bd3bae5b1840f9c3f2037 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#!/usr/bin/env node
const net=require("net");
const WebSocket=require("uws");
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=[];
let linebuf="";
netconn=net.connect(upstream.port,upstream.host,()=>{
for(const item of buffer){
netconn.write(item+"\n");
}
buffer=[];
});
netconn.on("close",()=>{
sock.close();
});
netconn.on("data",(data)=>{
linebuf+=data;
let idx;
while((idx=linebuf.indexOf("\n"))!=-1){
sock.send(linebuf.slice(0,idx));
linebuf=linebuf.slice(idx+1);
}
});
sock.on("close",()=>{
netconn.end();
});
sock.on("message",(data)=>{
if(netconn.connecting)buffer.push(data);
else netconn.write(data+"\n");
});
});
process.on("SIGINT",()=>{
console.log("Closing websocket server...");
server.close();
});
|