How to use the ws function in ws

To help you get started, we’ve selected a few ws examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github radixdlt / radixdlt-js / test / integration / MetaDataAtom.spec.ts View on Github external
it('4. should fail with invalid json', function(done) {
        // Get a raw websocket
        const socket = new WebSocket(nodeConnection.address)

        socket.onopen = async function() {
            socket.onmessage = function(event) {
                const response = JSON.parse(event.data)

                if ('error' in response) {
                    done()
                }
            }

            // Get an atom
            const metaDataVal = '123456'
            const brokenMetaDataVal = '123"456'

            buildTestAtom({
                test: metaDataVal,
github wechaty / wechaty / src / io.ts View on Github external
// const auth = 'Basic ' + new Buffer(this.setting.token + ':X').toString('base64')
    const auth = 'Token ' + this.options.token
    const headers = { Authorization: auth }

    if (!this.options.apihost) {
      throw new Error('no apihost')
    }
    let endpoint = 'wss://' + this.options.apihost + '/v0/websocket'

    // XXX quick and dirty: use no ssl for APIHOST other than official
    // FIXME: use a configuarable VARIABLE for the domain name at here:
    if (!/api\.chatie\.io/.test(this.options.apihost)) {
      endpoint = 'ws://' + this.options.apihost + '/v0/websocket'
    }

    const ws = this.ws = new WebSocket(endpoint, this.protocol, { headers })

    ws.on('open',     () => this.wsOnOpen(ws))
    ws.on('message',  data => this.wsOnMessage(data))
    ws.on('error',    e => this.wsOnError(e))
    ws.on('close',    (code, reason) => this.wsOnClose(ws, code, reason))

    await new Promise((resolve, reject) => {
      ws.once('open', resolve)
      ws.once('error', reject)
      ws.once('close', reject)
    })

    return ws
  }
github imxeno / tradingview-scraper / src / TradingViewAPI.ts View on Github external
private _resetWebSocket() {
    this.tickerData = {};
    this.subscriptions = [];

    this.session = this._generateSession();
    this.sessionRegistered = false;
    this.ws = new WebSocket("wss://data.tradingview.com/socket.io/websocket", {
      origin: "https://data.tradingview.com"
    });
    this.ws.on("message", (data: string) => {
      const packets = SIO.parseMessages(data);
      packets.forEach((packet: any) => {
        // reply to keepalive packets
        if (packet["~protocol~keepalive~"]) {
          this._sendRawMessage("~h~" + packet["~protocol~keepalive~"]);
        } else if (packet.session_id) {
          // reply to successful connection packet

          // connecting as unauthorized user

          this._sendMessage("set_auth_token", ["unauthorized_user_token"]);

          // registering default ticker session
github omeroot / socketbox / test / socketbox.js View on Github external
wss.on('listening', () => {
        connection = new WebSocket('ws://localhost:8081');
      });
    });
github wechaty / wechaty / src / puppet-padchat / auth-server.ts View on Github external
function proxyWs(downStream: WebSocket): void {

  const weiId = cuid()
  let buf: string[] = []

  const upStream = new WebSocket(
    ENDPOINT,
    { perMessageDeflate: true },
  )

  upStream.on('open',     () => {
    console.log('upStream on(open)')
    if (buf.length > 0) {
      console.log('upStream on(open) buf.length: ' + buf.length)
      buf.forEach(data => upStream.send(data))
      buf = []
    }
  })
  upStream.on('error',    e => {
    console.error('upStream on(error) ' + e)
    downStream.close()
  })
github HydroProtocol / hydro-client-js / src / lib / HydroWatcher.ts View on Github external
private initIfNeeded() {
    if (!this.socket || this.socket.readyState === WebSocket.CLOSED) {
      this.socket = new WebSocket(this.getWebsocketUrl());
      this.socket.on('message', (message: string) => {
        this.receiveMessage(message);
      });
      this.socket.on('close', () => {
        this.initIfNeeded();
      });
      this.socket.on('open', () => {
        while (this.messageQueue.length > 0) {
          let message = this.messageQueue.shift();
          this.socket && this.socket.send(message);
        }
      });
    }
  }
github Syncano / syncano-node / packages / cli / src / utils / sockets / sockets.js View on Github external
getTraces (lastId) {
    const url = [
      `https://${session.getHost()}/v2/instances/${session.project.instance}/channels/eventlog/poll/`,
      '?transport=websocket',
      `&api_key=${session.settings.account.getAuthKey()}`,
      `&room=${`socket:${this.name}`}`
    ].join('')

    return new WebSocket(url)
  }
github discordjs / discord.js / src / Voice / VoiceConnection.js View on Github external
dns.lookup(this.endpoint, (err, address, family) => {
			var vWS = self.vWS = new WebSocket("wss://" + this.endpoint, null, { rejectUnauthorized: false });
			this.endpoint = address;
			var udpClient = self.udp = udp.createSocket("udp4");

			var firstPacket = true;

			var discordIP = "", discordPort = "";

			udpClient.bind({ exclusive: true });
			udpClient.on('message', function (msg, rinfo) {
				var buffArr = JSON.parse(JSON.stringify(msg)).data;
				if (firstPacket === true) {
					for (var i = 4; i < buffArr.indexOf(0, i); i++) {
						discordIP += String.fromCharCode(buffArr[i]);
					}
					discordPort = msg.readUIntLE(msg.length - 2, 2).toString(10);
github dosyago / supreme-architect / zombie-lord / connection.js View on Github external
async function makeZombie({port:port = 9222} = {}) {
  const {webSocketDebuggerUrl} = await fetch(`http://localhost:${port}/json/version`).then(r => r.json());
  const socket = new ws(webSocketDebuggerUrl);
  const Resolvers = {};
  const Handlers = {};
  socket.on('message', handle);
  let id = 0;
  
  async function send(method, params = {}, sessionId) {
    const message = {
      method, params, sessionId, 
      id: ++id
    };
    const key = `${sessionId||ROOT_SESSION}:${message.id}`;
    let resolve;
    const promise = new Promise(res => resolve = res);
    Resolvers[key] = resolve; 
    socket.send(JSON.stringify(message));
    return promise;
github webdriverio-boneyard / remotedriver / lib / remoteProtocolMultiplexer.js View on Github external
createNewUpstreamSocket (wsUpstreamUrl) {
        const upstreamSocket = new WebSocket(wsUpstreamUrl)
        upstreamSocket.on('message', (message) => {
            const msgObj = JSON.parse(message)

            /**
             * this is an event, broadcast it
             */
            if (!msgObj.id) {
                const clientCnt = this.upstreamMap[wsUpstreamUrl].clients.length
                log.info(`broadcast message to ${clientCnt} clients:`, colors.cyan(message))
                this.upstreamMap[wsUpstreamUrl].clients.forEach((s) => s.send(message))
            } else {
                const idMap = this.upstreamMap[wsUpstreamUrl].localIdToRemote[msgObj.id]
                msgObj.id = idMap.id

                log.info(colors.blue(String(idMap.client._id)) + '> ' + colors.yellow(idMap.message))
                log.info(colors.blue(String(idMap.client._id)) + '> ' + colors.green(JSON.stringify(msgObj)))

ws

Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js

MIT
Latest version published 4 days ago

Package Health Score

94 / 100
Full package analysis