2023-01-18 08:19:39 +00:00
|
|
|
import { Duplex, Callback } from "streamx";
|
|
|
|
interface SocketOptions {
|
|
|
|
allowHalfOpen?: boolean;
|
|
|
|
remoteAddress?: string;
|
|
|
|
remotePort?: number;
|
|
|
|
cb?: Function;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default class Socket extends Duplex {
|
|
|
|
private _ws: WebSocket;
|
|
|
|
|
|
|
|
constructor({ remoteAddress, remotePort, cb }: SocketOptions = {}) {
|
|
|
|
super();
|
|
|
|
this._ws = new WebSocket(`wss://${remoteAddress}/webirc`);
|
|
|
|
|
|
|
|
["message", "end", "close", "error"].forEach((event) => {
|
|
|
|
this._ws.addEventListener(event, (...args) => {
|
|
|
|
let sendEvent = event;
|
|
|
|
let sendData = args;
|
|
|
|
|
|
|
|
if (event === "message") {
|
|
|
|
sendEvent = "data";
|
2023-01-18 09:57:23 +00:00
|
|
|
sendData[0] = ((args[0] as MessageEvent).data + "\n") as any;
|
2023-01-18 08:19:39 +00:00
|
|
|
}
|
|
|
|
// @ts-ignore
|
|
|
|
return this.emit(sendEvent, ...sendData);
|
|
|
|
});
|
|
|
|
this._ws.addEventListener("open", cb as any);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
_write(data: any, cb: Callback) {
|
|
|
|
this._ws.send(data);
|
|
|
|
cb();
|
|
|
|
}
|
2023-01-18 09:57:23 +00:00
|
|
|
_destroy(cb: any) {
|
|
|
|
this._ws.close();
|
|
|
|
cb();
|
|
|
|
}
|
2023-01-18 08:19:39 +00:00
|
|
|
setEncoding() {}
|
|
|
|
}
|
|
|
|
export function connect(
|
|
|
|
port: number,
|
|
|
|
host: string,
|
|
|
|
opts = {},
|
|
|
|
cb: Function
|
|
|
|
): Socket {
|
|
|
|
return new Socket({
|
|
|
|
remotePort: port,
|
|
|
|
remoteAddress: host,
|
|
|
|
cb,
|
|
|
|
});
|
|
|
|
}
|