How to use the ws.Server 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 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 Orange-OpenSource / wamp.rt / lib / router.js View on Github external
// calling script, just filter out the results
                cb([protocols[i-1]], callback);
            } else {
                callback(result, result ? protocols[i-1] : null);
            }
        };
    }
    var _rpcs = {};
    var _pending = {};
    var _sessions = {};
    var _topics = {};
    var _trace = function (msg) {
        log.trace('[ROUTER] ' + msg);
    };
    // Instantiate WebSocketServer
    var _wss = new WebSocketServer(_options);
    // Create a Session object for the lifetime of each
    // WebSocket client object
    _wss.on('connection', function (wsclient) {
        var id = tools.randomId();
        _sessions[id] = new Session(this, wsclient);
        wsclient.on('close', function() {
            _sessions[id].cleanup();
            delete _sessions[id];
        });
    }.bind(this));

    this.close = function() {
        _wss.close();
    };

    // RPC Management
github flutter-webrtc / flutter-webrtc-server / src / server / CallHandler.js View on Github external
var app = express();
import fs from 'fs';
import ws from 'ws';
import https from 'https';
var options = {
  key: fs.readFileSync('../../certs/key.pem'),
  cert: fs.readFileSync('../../certs/cert.pem')
};
var serverPort = (process.env.PORT || 4443);


let server = https.createServer(options, app).listen(serverPort, () => {
  console.log("flutter webrtc server started");
});

let wss = new ws.Server({ server: server });

export default class CallHandler {

  init() {

    wss.on('connection', (client) => {
      console.log('connection');

      client.on("close", data => {

        var msg = new Object();
        msg.type = "leave";
        msg.data = JSON.stringify(client.sessionId);

        wss.clients.forEach(function (cur_client) {
          cur_client.send(JSON.stringify(msg));
github skepticfx / wshook / examples / server.js View on Github external
const WebSocket = require('ws')

console.log('open the file ' + process.cwd() + '/examples/example.html in a browser')
const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', function connection (ws) {
  console.log('connection')
  ws.on('message', function incoming (message) {
    console.log('received: %s', message)
    ws.send(message)
    console.log('echoed back...')
  })

})
github apache / incubator-weex-cli / build / preview.js View on Github external
startWebSocket: function startWebSocket(fileName) {
    var port = this.params.websocketPort;
    var wss = wsServer({ port: port });
    var self = this;
    npmlog.info(new Date() + ('WebSocket  is listening on port ' + port));
    wss.on('connection', function connection(ws) {
      ws.on('message', function incoming(message) {
        npmlog.info('received: %s', message);
      });
      ws.send("ws server ok");
      self.wsConnection = ws;
      self.watchForWSRefresh(fileName);
    });
  },
  watchForWSRefresh: function watchForWSRefresh(fileName) {
github microsoft / vscode-chrome-debug-core / src / chrome / crdpMultiplexing / webSocketToLikeSocketProxy.ts View on Github external
public start(): void {
        this._server = new WebSocket.Server({ port: this._port }, () => {
            logger.log(`CRDP Proxy listening on: ${this._port}`);
        });

        this._socket.on('close', () => {
            logger.log('CRDP Proxy shutting down');
            this._server.close(() => {
                if (this._currentlyOpenedWebSocket !== null) {
                    this._currentlyOpenedWebSocket.close();
                    logger.log('CRDP Proxy succesfully shut down');
                }

                return {};
            });
        });

        this._server.on('connection', openedWebSocket => {
github scality / cloudserver / managementAgent.js View on Github external
startServer() {
        this.wss = new WebSocket.Server({
            port: this.port,
            clientTracking: true,
            path: '/watch',
        });

        this.wss.on('connection', this.onConnection.bind(this));
        this.wss.on('listening', this.onListening.bind(this));
        this.wss.on('error', this.onError.bind(this));

        setInterval(this.checkBrokenConnections.bind(this),
                    CHECK_BROKEN_CONNECTIONS_FREQUENCY_MS);

        addOverlayMessageListener(this.onNewOverlay.bind(this));
    }
github emscripten-core / emscripten / third_party / websockify / other / websockify.js View on Github external
webServer.listen(source_port, function() {
    wsServer = new WebSocketServer({server: webServer,
                                    handleProtocols: selectProtocol});
    wsServer.on('connection', new_client);
});
github callstack / haul / packages / haul-core-legacy / src / compiler / createWebSocketServer.js View on Github external
module.exports = async function createWebSocketServer() {
  const httpServer = http.createServer();
  const webSocketServer = new Server({
    server: httpServer,
    perMessageDeflate: false,
    maxPayload: 200 * 1024 * 1024,
  });

  const port = await getPort();
  httpServer.listen(port);

  return webSocketServer;
};

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