How to use ws - 10 common examples

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 sebpiq / rhizome / test / helpers-backend.js View on Github external
, rimraf = require('rimraf')
  , oscServer = require('../lib/osc/Server')
  , oscTransport = require('../lib/osc/transport')
  , connections = require('../lib/connections')
  , coreServer = require('../lib/core/server')
  , coreMessages = require('../lib/core/messages')
  , ValidationError = require('../lib/core/errors').ValidationError
  , utils = require('../lib/core/utils')
  , helpersEverywhere = require('./helpers-everywhere')
_.extend(exports, helpersEverywhere)

// The directory we use for storing persisted data in tests
var testDbDir = exports.testDbDir = '/tmp/rhizome-test-db'

// For testing : we need to add standard `removeEventListener` method cause `ws` doesn't implement it.
WebSocket.prototype.removeEventListener = function(name, cb) {
  var handlerList = this._events[name]
  handlerList = _.isFunction(handlerList) ? [handlerList] : handlerList
  this._events[name] = _.reject(handlerList, (other) => other._listener === cb)
}

// Helper to create dummy web clients. Callack is called only when sockets all opened.
exports.dummyWebClients = function(wsServer, clients, done) {
  var countBefore = wsServer._wsServer.clients.length 
    , url, socket, sockets = []
  async.series(clients.map((client) => {
    return (next) => {
      _.defaults(client, { query: {} })
      client.query.dummies = ''
      url = 'ws://localhost:' + client.port + '/?' + querystring.stringify(client.query)
      socket = new WebSocket(url)
      _dummyWebClients.push(socket)
github sebpiq / rhizome / test / lib / websockets / Server-tests.js View on Github external
helpers.dummyWebClients(wsServer, dummyClients, (err, sockets, messages) => {
          if (err) throw err

          assert.deepEqual(
            _.pluck(Array.from(wsServer._wsServer.clients).slice(0, 5), 'readyState'), 
            _.range(5).map(() => WebSocket.OPEN)
          )

          // Check that the last socket received connection rejected
          var lastMsg = messages.pop()
          assert.equal(lastMsg.length, 2)
          assert.equal(lastMsg[0], 1)
          assert.ok(_.isString(lastMsg[1]))
          assert.equal(_.last(Array.from(wsServer._wsServer.clients)).readyState, WebSocket.CLOSING)
          
          // Check that all sockets before got connection accepted
          messages.forEach((msg) => {
            assert.equal(msg.length, 2)
            assert.equal(msg[0], 0)
            assert.ok(_.isString(msg[1]))
          })
          done()
        })
      })
github opporty-com / Plasma-Cash / plasma-core / src / child-chain / lib / PN.js View on Github external
};
      client._send = (code, payload) => {
        // console.log("send to ", req.connection.remoteAddress, code);
        seq++;
        if (seq >= 255) seq = 0;
        const countChunk = Math.ceil(payload.length / ChunkSize);

        this.chunks[seq] = {
          code,
          countChunk,
          payload
        };
        client._sendChunk(seq, 0);
      };
      const duplex = WebSocket.createWebSocketStream(client, {compress: false, binary: true});

      duplex.on('error', err => console.log(err));

      client.ostream.pipe(duplex);
      duplex.pipe(client.istream).on('data', packet => {
        const {code, seq, versionProtocol, length, payload, chunkNumber, countChunk} = packet;
        if (code === MESSAGE_CODES.CHUNK_RECEIVE)
          return client._sendChunk(seq, chunkNumber + 1);

        this.emit(MESSAGE_CODE[code], payload, client);
      });

      client.isAlive = true;
      client.on('pong', this._heartbeat.bind(client));
      client.on('error', err => console.log(4, err));
github bitshares / bitshares-ui / plasma / programs / wallet-server / src / server.js View on Github external
export default function createServer() {
    // const createStoreWithMiddleware = applyMiddleware( createMiddleware() )(createStore)
    // const store = createStoreWithMiddleware( reducer )
    const store = createStore( reducer )

    let wss = new WebSocketServer({port: npm_package_config_network_port})
    wss.on('listening', ()=>{ if(global.INFO) console.log('INFO\tserver listening port %d', npm_package_config_network_port) })
    wss.on('close', ()=>{ if(global.INFO) console.log('INFO\tserver closed port %d', npm_package_config_network_port) })
    wss.on('error', error =>{ console.error('ERROR\tserver onerror', error, 'stack', error.stack) })
     
    // Limit number of requests per hour by IP
    if(global.INFO) console.log("INFO\tserver\tLimit by IP address", {
        max: ratelimitConfig.max,
        duration: ratelimitConfig.duration/1000/60+' min'
    })
    
    wss.on("connection", ws => { try {
    
        sockets = sockets.add(ws)
        if(global.INFO) console.log('INFO\tserver NEW SOCKET',"IP", ipAddress(ws), "Total sockets", sockets.count())
        
        ws.on('close', ()=> { try {
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 traumverloren / speech-to-image-necklace / app.js View on Github external
currentInterval = setInterval(() => {
        // if current word hasn't changed, don't send another request to image search api
        if (currentWord != nextWord) {
          currentWord = nextWord;
          findImage(currentWord);
        }
        try {
          if (ws.readyState != WebSocket.CLOSED) {
            // send image url to client
            ws.send(currentImageURL);
          }
        } catch (e) {
          console.log(e);
        }
      }, 1000);
    }
github OgarProject / Ogar / src / GameServer.js View on Github external
for (var i = 0; i < l; i++) {
            buffer[i] = array[o + i];
        }

        return buffer;
    }

    //if (this.readyState == WebSocket.OPEN && (this._socket.bufferSize == 0) && packet.build) {
    if (this.readyState == WebSocket.OPEN && packet.build) {
        var buf = packet.build();
        this.send(buf, { binary: true });
    } else if (!packet.build) {
        // Do nothing
    } else {
        this.readyState = WebSocket.CLOSED;
        this.emit('close');
        this.removeAllListeners();
    }
};
github h3poteto / megalodon / src / web_socket.ts View on Github external
setTimeout(() => {
      // Skip reconnect when client is connecting.
      // https://github.com/websockets/ws/blob/7.2.1/lib/websocket.js#L365
      if (this._client && this._client.readyState === WS.CONNECTING) {
        return
      }

      if (this._reconnectCurrentAttempts < this._reconnectMaxAttempts) {
        this._reconnectCurrentAttempts++
        this._clearBinding()
        if (this._client) {
          // In reconnect, we want to close the connection immediately,
          // because recoonect is necessary when some problems occur.
          this._client.terminate()
        }
        // Call connect methods
        console.log('Reconnecting')
        this._client = this._connect(this.url, this.stream, this._accessToken, this.headers, this.proxyConfig)
        this._bindSocket(this._client)
      }
github udevbe / westfield / server / node / example.browserclient / nodeserver.js View on Github external
client.onFlush = wireMsg => {
    if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
      // Fail silently as we will soon receive the close event which will trigger the cleanup.
      return
    }

    try {
      ws.send(wireMsg, error => {
        if (error !== undefined) {
          console.error(error)
          ws.close()
        }
      })
    } catch (error) {
      console.error(error)
      ws.close()
    }
  }

ws

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

MIT
Latest version published 6 months ago

Package Health Score

89 / 100
Full package analysis