WSServer.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import ws from "ws";
  2. class WebSocketServer {
  3. server?: ws.Server;
  4. button?:HTMLElement;
  5. constructor(private port: number = 8045){
  6. if(! (!isNaN(port) && port > 0 && port < 65535)){
  7. throw new Error("Malicious port")
  8. }
  9. }
  10. status(): boolean{
  11. return !!this.server;
  12. }
  13. changePort(newport: number){
  14. if(this.status()){
  15. throw new Error("Can't change port while server is running");
  16. }
  17. this.port = newport;
  18. }
  19. start(){
  20. if(this.status()){
  21. console.log("Trying to start websocket when it is already running");
  22. return
  23. }
  24. this.changePort(window.settings.options.port);
  25. this.server = new ws.Server({
  26. port: this.port
  27. });
  28. this.server.on("close", ()=>{
  29. this.server = undefined;
  30. })
  31. }
  32. stop(){
  33. if(!this.status()){
  34. console.log("Trying to stop websocket when it's not running");
  35. return
  36. }
  37. this.server.close();
  38. }
  39. bindButton(btn: HTMLElement){
  40. this.button = btn;
  41. }
  42. updateElement(){
  43. let status = document.getElementById("wssStatus");
  44. if(this.status()){
  45. status.innerText = "Online"
  46. status.style.color = "Green";
  47. if(this.button)
  48. this.button.innerText = "Stop";
  49. }else{
  50. status.innerText = "Offline"
  51. status.style.color = "red";
  52. if(this.button)
  53. this.button.innerText = "Start";
  54. }
  55. }
  56. sendToAll(msg: string){
  57. if(this.server){
  58. this.server.clients.forEach((value) => {
  59. value.send(msg)
  60. })
  61. }
  62. }
  63. }
  64. export default WebSocketServer;