Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "isomorphic-ws in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'isomorphic-ws' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

new Promise((resolve, reject) => {
      this.current_reject = reject;
      this.current_resolve = resolve;

      try {
        this.ws = new WebSocket(server);
      } catch (error) {
        this.ws = { readyState: 3, close: () => {} }; // DISCONNECTED
        reject(new Error("Invalid url", server, " closed"));
        // return this.close().then(() => {
        //     console.log("Invalid url", ws_server, " closed");
        //     // throw new Error("Invalid url", ws_server, " closed")
        //     // return this.current_reject(Error("Invalid websocket url: " + ws_server));
        // })
      }

      this.ws.onopen = this.onOpen;
      this.ws.onerror = this.onError;
      this.ws.onmessage = this.onMessage;
      this.ws.onclose = this.onClose;

      this.connectionTimeout = setTimeout(() => {
const { hostname, port } = window.location;
      url = `${protocol}//${hostname}:${port}/${path}`;
    } else {
      const protocol = config.useHttps ? 'wss:' : 'ws:';
      const { ip, port } = config;
      url = `${protocol}//${ip}:${port}/${path}`;
    }

    const queryParams = `clientType=${clientType}&key=${key}`;

    // ----------------------------------------------------------
    // init string socket
    // ----------------------------------------------------------
    const stringSocketUrl = `${url}?binary=0&${queryParams}`;

    this.ws = new WebSocket(stringSocketUrl);
    log(`string socket initialized - url: ${stringSocketUrl}`);

    const stringSocketPromise = new Promise((resolve, reject) => {
      this.ws.addEventListener('open', resolve);
    });

    // parse incoming messages for pubsub
    this.ws.addEventListener('message', e => {
      const [channel, args] = unpackStringMessage(e.data);
      this._emit(false, channel, ...args);
    });

    // broadcast all `WebSocket` native events
    [ 'open',
      'close',
      'error',
async function processData(data) {
    const buff = Buffer.alloc(data.length + 1);

    buff.writeInt8(streamNum, 0);
    if (data instanceof Buffer) {
      data.copy(buff, 1);
    } else {
      buff.write(data, 1);
    }

    let i = 0;

    try {
      for (; i < tryLimit; ++i) {
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(buff);
          break;
        } else {
          ws = await createWS()
        }
      }
    } catch (e) {
      // TODO: Сonsider to log network errors.
      console.error(e)
      stdin.end()
    }

    if (i >= tryLimit) {
      stdin.end()
    }
  }
public disconnect(): void {
    if (!this.socket) {
      throw new Error("Socket undefined. This must be called after connecting.");
    }

    this.clearTimeout();

    switch (this.socket.readyState) {
      case WebSocket.OPEN:
        this.socket.close(1000 /* Normal Closure */);
        break;
      case WebSocket.CLOSED:
        // nothing to be done
        break;
      case WebSocket.CONNECTING:
        // imitate missing abort API
        this.socket.onopen = () => 0;
        this.socket.onclose = () => 0;
        this.socket.onerror = () => 0;
        this.socket.onmessage = () => 0;
        this.socket = undefined;
        if (this.closeHandler) {
          this.closeHandler({ wasClean: false, code: 4001 });
        }
        break;
      case WebSocket.CLOSING:
        // already closing. Let it proceed
        break;
break;
      case WebSocket.CLOSED:
        // nothing to be done
        break;
      case WebSocket.CONNECTING:
        // imitate missing abort API
        this.socket.onopen = () => 0;
        this.socket.onclose = () => 0;
        this.socket.onerror = () => 0;
        this.socket.onmessage = () => 0;
        this.socket = undefined;
        if (this.closeHandler) {
          this.closeHandler({ wasClean: false, code: 4001 });
        }
        break;
      case WebSocket.CLOSING:
        // already closing. Let it proceed
        break;
      default:
        throw new Error(`Unknown readyState: ${this.socket.readyState}`);
    }
  }
return new Promise((resolve, reject) => {
      if (!this.socket) {
        throw new Error("Socket undefined. This must be called after connecting.");
      }

      if (this.closed) {
        throw new Error("Socket was closed, so no data can be sent anymore.");
      }

      // this exception should be thrown by send() automatically according to
      // https://developer.mozilla.org/de/docs/Web/API/WebSocket#send() but it does not work in browsers
      if (this.socket.readyState !== WebSocket.OPEN) {
        throw new Error("Websocket is not open");
      }

      if (environmentIsNodeJs()) {
        this.socket.send(data, err => (err ? reject(err) : resolve()));
      } else {
        // Browser websocket send method does not accept a callback
        this.socket.send(data);
        resolve();
      }
    });
  }
public disconnect(): void {
    if (!this.socket) {
      throw new Error("Socket undefined. This must be called after connecting.");
    }

    this.clearTimeout();

    switch (this.socket.readyState) {
      case WebSocket.OPEN:
        this.socket.close(1000 /* Normal Closure */);
        break;
      case WebSocket.CLOSED:
        // nothing to be done
        break;
      case WebSocket.CONNECTING:
        // imitate missing abort API
        this.socket.onopen = () => 0;
        this.socket.onclose = () => 0;
        this.socket.onerror = () => 0;
        this.socket.onmessage = () => 0;
        this.socket = undefined;
        if (this.closeHandler) {
          this.closeHandler({ wasClean: false, code: 4001 });
        }
        break;
      case WebSocket.CLOSING:
        // already closing. Let it proceed
        break;
      default:
        throw new Error(`Unknown readyState: ${this.socket.readyState}`);
    }
private init(): void {
    this.ws = new WebSocket(this.provider);
    this.ws.onopen = (): void => {
      window.console.log("[antenna-ws] connected");
    };
    this.ws.onclose = (): void => {
      window.console.log("[antenna-ws] disconnected");
    };
  }
createGatewayServer = (internalRequestHandler, connectionHandler = defaultConnectionHandler, options = { }) => {
    const serverOption = {}
    if ('port' in options) {
      serverOption.port = options.port
    } else if ('server' in options)  {
      serverOption.server = options.server
    } else if ('noServer' in options) {
      serverOption.noServer = options.noServer
    }
    const server = new WebSocket.Server(serverOption)
    server.on('connection', async (socket, req) => {
      try {
        const { id } = await connectionHandler(socket, req)
        socket.id = id
        this.clientMap[id] = socket
        socket.on('message', (msg) => this.handleGatewayMessage(msg, socket))
        socket.on('close', () => {
          delete this.clientMap[id]
        })
      } catch (e) {
        console.log(e)
        socket.terminate()
      }
    })
    this.replaceInternalSocket(internalRequestHandler)
    return server
async _getWebsocket () {
    const wsUrl = 'ws' + (this.instance.secure ? 's' : '') + '://' + this.instance.host + ':' + this.instance.port + '/Websocket?wrapper_key=' + this.wrapperKey
    let wsClient

    if (!this.multiuser.masterAddress) {
      wsClient = new WebSocket(wsUrl)
    } else {
      wsClient = new WebSocket(wsUrl, [], { headers: { Cookie: 'master_address=' + this.multiuser.masterAddress } })
    }

    wsClient.onmessage = this._onRequest.bind(this)
    wsClient.onopen = this._onOpenWebsocket.bind(this)
    wsClient.onerror = this._onErrorWebsocket.bind(this)
    wsClient.onclose = this._onCloseWebsocket.bind(this)

    return wsClient
  }

Is your System Free of Underlying Vulnerabilities?
Find Out Now