ws#WebSocketServer TypeScript Examples

The following examples show how to use ws#WebSocketServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: server.ts    From eufy-security-ws with MIT License 6 votes vote down vote up
async start(): Promise<void> {
        this.server = createServer();
        this.wsServer = new WebSocketServer({ server: this.server });
        this.sockets = new ClientsController(this.driver, this.logger);
        this.wsServer.on("connection", (socket, request) => this.sockets?.addSocket(socket, request));

        this.logger.debug(`Starting server on host ${this.options.host}, port ${this.options.port}`);

        this.server.on("error", this.onError.bind(this));
        this.server.listen(this.options.port, this.options.host);
        await once(this.server, "listening");
        this.emit("listening");
        this.logger.info(`Eufy Security server listening on host ${this.options.host}, port ${this.options.port}`);
        await this.driver.connect()
    }
Example #2
Source File: v1.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
export function setupWsApi(
  server: WebSocketServer,
  logs: LogStream,
  options: { apiToken?: string },
  adminServer?: AdminServer
) {
  server.on('connection', (socket, req) => {
    const needsAuth = !!options.apiToken
    if (needsAuth && !authenticateWsConnection(req, options.apiToken)) {
      logs.log('ws client failed authentication')
      socket.send(
        JSON.stringify({
          type: 'auth-failed',
          msg: 'authentication failed',
          ts: new Date().toISOString()
        })
      )
      socket.close()
      return
    }
    if (!needsAuth) logs.log('ws client connected [ authentication DISABLED ]')
    else logs.log('ws client connected [ authentication ENABLED ]')

    if (adminServer) adminServer.onConnection(socket)
  })
}
Example #3
Source File: Studio.ts    From cli with Apache License 2.0 5 votes vote down vote up
export function start(filePath: string, port: number = DEFAULT_PORT): void {
  if (!isValidFilePath(filePath)) {
    throw new SpecificationFileNotFound(filePath);
  }
  chokidar.watch(filePath).on('all', (event, path) => {
    switch (event) {
    case 'add':
    case 'change':
      getFileContent(path).then((code:string) => {
        messageQueue.push(JSON.stringify({
          type: 'file:changed',
          code,
        }));
        sendQueuedMessages();
      });
      break;
    case 'unlink':
      messageQueue.push(JSON.stringify({
        type: 'file:deleted',
        filePath,
      }));
      sendQueuedMessages();
      break;
    }
  });

  const server = createServer((request, response) => {
    return serveHandler(request, response, {
      public: resolve(__dirname, '../../node_modules/@asyncapi/studio/build'),
    });
  });

  server.on('upgrade', (request, socket, head) => {
    if (request.url === '/live-server') {
      wsServer.handleUpgrade(request, socket, head, (sock: any) => {
        wsServer.emit('connection', sock, request);
      });
    } else {
      socket.destroy();
    }
  });

  const wsServer = new WebSocketServer({ noServer: true });

  wsServer.on('connection', (socket: any) => {
    sockets.push(socket);
    getFileContent(filePath).then((code: string) => {
      messageQueue.push(JSON.stringify({
        type: 'file:loaded',
        code,
      }));
      sendQueuedMessages();
    });

    socket.on('message', (event: string) => {
      try {
        const json:any = JSON.parse(event);
        if (json.type === 'file:update') {
          saveFileContent(filePath, json.code);
        } else {
          console.warn('Live Server: An unknown event has been received. See details:');
          console.log(json);
        }
      } catch (e) {
        console.error(`Live Server: An invalid event has been received. See details:\n${event}`);
      }      
    });
  });
  
  wsServer.on('close', (socket: any) => {
    sockets.splice(sockets.findIndex(s => s === socket));
  });

  server.listen(port, () => {
    const url = `http://localhost:${port}?liveServer=${port}`;
    console.log(`Studio is running at ${url}`);
    console.log(`Watching changes on file ${filePath}`);
    open(url);
  });
}
Example #4
Source File: server.ts    From eufy-security-ws with MIT License 5 votes vote down vote up
private wsServer?: WebSocketServer;
Example #5
Source File: index.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
export default async function setupAPI(
  node: Hopr,
  logs: LogStream,
  stateOps: StateOps,
  options: {
    api: boolean
    apiPort: number
    apiHost: string
    admin: boolean
    adminPort: number
    adminHost: string
    apiToken?: string
  },
  adminServer?: AdminServer // required by WS v1 (hopr-admin)
) {
  // creates server for Rest API v1, v2 and WS v2
  if (options.api) {
    debugLog('Enabling Rest API v1, v2 and WS v2')
    const service = express()
    const server = http.createServer(service)

    apiV1.setupRestApi(service, '/api/v1', node, logs, stateOps, options)
    apiV2.setupRestApi(service, '/api/v2', node, stateOps, options)
    apiV2.setupWsApi(server, new WebSocketServer({ noServer: true }), node, logs, options)

    server
      .listen(options.apiPort, options.apiHost, () => {
        logs.log(`API server on ${options.apiHost} listening on port ${options.apiPort}`)
      })
      .on('error', (err: any) => {
        logs.log(`Failed to start API server: ${err}`)

        // bail out, fail hard because we cannot proceed with the overall
        // startup
        throw err
      })
  }

  // deprecated: creates WS v1 server for hopr-admin
  if (options.admin && adminServer?.server) {
    debugLog('Enabling WS v1')
    apiV1.setupWsApi(new WebSocketServer({ server: adminServer.server }), logs, options, adminServer)

    logs.log(`deprecated WS admin API server on ${options.adminHost} listening on port ${options.adminPort}`)
  }
}
Example #6
Source File: v2.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
export function setupWsApi(
  server: Server,
  wss: WebSocketServer,
  node: Hopr,
  logStream: LogStream,
  options: { apiToken?: string }
) {
  // before upgrade to WS, we perform various checks
  server.on('upgrade', function upgrade(req, socket, head) {
    debugLog('WS client attempt to upgrade')
    const path = removeQueryParams(req.url)
    const needsAuth = !!options.apiToken

    // check if path is supported
    if (!Object.values(WS_PATHS).includes(path)) {
      debugLog(`WS client path '${path}' does not exist`)
      socket.end('HTTP/1.1 404 Not Found\r\n\r\n', () => socket.destroy())
      return
    }

    // check if request is authenticated
    if (needsAuth && !authenticateWsConnection(req, options.apiToken)) {
      debugLog('WS client failed authentication')
      socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n', () => socket.destroy())
      return
    }

    // log connection status
    if (!needsAuth) debugLog('WS client connected [ authentication DISABLED ]')
    else debugLog('WS client connected [ authentication ENABLED ]')

    // upgrade to WS protocol
    wss.handleUpgrade(req, socket, head, function done(socket_) {
      wss.emit('connection', socket_, req)
    })
  })

  wss.on('connection', (socket, req) => {
    debugLog('WS client connected!')
    const path = removeQueryParams(req.url)

    socket.on('error', (err: string) => {
      debugLog('WS error', err.toString())
    })

    if (path === WS_PATHS.MESSAGES) {
      node.on('hopr:message', (msg: Uint8Array) => {
        socket.send(msg.toString())
      })
    } else if (path === WS_PATHS.LEGACY_STREAM) {
      logStream.addMessageListener((msg) => {
        if (msg.type !== 'message') {
          socket.send(
            JSON.stringify({
              type: msg.type,
              timestamp: msg.ts,
              content: msg.msg
            })
          )
        }
      })
    } else {
      // close connection on unsupported paths
      socket.close(1000)
    }
  })
}