You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

import MessageQueue from "./message.js";
import {addEventListenerHack, uuidv4, is_uuid} from "./util";
function Pipe(ws)
{
this.socket =ws;
this.id = uuidv4();
}
const P = Pipe.prototype;
P.connect = async function(message) {
const socket = new MessageQueue(this.socket);
socket.send0(JSON.stringify({com: 'open', id: this.id, msg: message}));
try {
let msg;
while ((msg = await socket.read()) !== undefined) {
try {
msg = JSON.parse(msg);
} catch(_){continue;}
if (msg.id === id && msg.com === 'resp') {
if (msg.message === 'accepted') {
const cli = new MessageQueue(this.socket);
let open=true;
cli.id = id;
cli.apply = (raw) => {
return JSON.stringify({message: raw, com: 'msg', id: id});
};
cli.premap = (raw) => {
try {
return JSON.parse(raw);
}catch(_) {return null;}
};
cli.filter = (json) => json?.id === 'id' && (json?.com === 'msg' || json?.com === 'resp' && json?.message === 'closing' && cli.close() && false);
cli.map = (json) => json?.message;
cli.on_close = (self) => {
if(open && self.id === id) { //in case of mistaken cloning
self.send0({com: 'close', message: 'closing', id: id});
open = false;
}
};
return cli;
} else {
console.log(`[${id}]: server responded with ${msg.message}: ${msg.reason}`);
return false;
}
}
}
} finally{
socket.close();
}
return undefined;
};
P.close = function() {
this.socket.close();
};
export default Pipe;