How to use websocket - 10 common examples

To help you get started, we’ve selected a few websocket 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 wallix / redemption / projects / browser_client_JS / js_websocket_proxy / ws_server.js View on Github external
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptwssockets for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});
wsServer.binaryType = 'arraybuffer';
//wsServer.setEncoding('binary');


function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}
github limpkin / mooltipass / mooltiapp / app / preload.js View on Github external
var server = http.createServer(function(request, response) {
	console.log((new Date()) + ' Received request for ' + request.url);
	response.writeHead(404);
	response.end();
}).on('error', (err) => {
  // handle errors here
  setTimeout( serverStartListening, 500);
});

serverStartListening = function() {
	server.listen(30035, function() {
		console.warn((new Date()) + ' Server is listening on port 30035');
	});
};

var wsServer = new WebSocketServer({
	httpServer: server,
	autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

var clients = {};
var connection;
wsServer.on('request', function(request) {
	if (!originIsAllowed(request.origin)) {
	  request.reject();
	  console.log( (new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
	  return;
github OlivierLD / raspberry-coffee / NMEA.multiplexer / wsnmea.parser.js View on Github external
console.log("AutoParsed (1):", auto, data);
                }
            } catch (err) {
                console.log(err);
                console.log("AutoParsed (2):", auto, data);
            }
        }
    } catch (err) {
        console.log(err);
    }
};

/**
 * WebSocket server
 */
var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. WebSocket request is just
    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
    httpServer: server
});

// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
    console.log((new Date()) + ' Connection from origin ' + request.origin + '.');

    // accept connection - you should check 'request.origin' to make sure that
    // client is connecting from your website
    // (http://en.wikipedia.org/wiki/Same_origin_policy)
    var connection = request.accept(null, request.origin);
    clients.push(connection);
    console.log((new Date()) + ' Connection accepted.');
github jesusprubio / bluebox-ng / utils / steroidsSocket.js View on Github external
'WS' : function () {
                var addr = self.transport.toLowerCase() +
                    '://' + self.target + ':' + self.port;

                if (self.wsPath) {
                    addr += '/' + self.wsPath;
                }
                self.megaSocket = new WebSocketClient({
                    tlsOptions   : {
                        rejectUnauthorized : false
                    }
                });

                setTimeout(timeoutCb, self.timeout);

                self.megaSocket.on('connectFailed', function (err) {
                    received = true; // to avoid the launch of our timeout error
                    if (!wsError) {
                        self.emit('error', {
                            type : 'socket: connectFailed',
                            data : err.toString()
                        });
                    }
                });
github Azure / azure-relay-node / hyco-websocket / lib / HybridConnectionsWebSocketServer.js View on Github external
if (typeof server.config.token === 'function') {
            // server.config.token is a function, call it periodically to renew the token
            tokenRenewDuration = new moment.duration(1, 'hours');
            token = server.config.token();
        } else {
            // server.config.token is a string, the token cannot be renewed automatically
            token = server.config.token;
        }

        headers = { 'ServiceBusAuthorization': token };
    };

    // This represents the token renew timer/interval, keep a reference in order to cancel it.
    var tokenRenewTimer = null;

    var client = new WebSocketClient();
    client.connect(server.listenUri, null, null, headers);
    client.on('connect', function(connection) {
        server.controlChannel = connection;
        server.controlChannel.on('error', function(event) {
            server.emit('error', event);
            clearInterval(tokenRenewTimer);
            if (!closeRequested) {
                connectControlChannel(server);
            }
        });

        server.controlChannel.on('close', function(event) {
            clearInterval(tokenRenewTimer);
            if (!closeRequested) {
                // reconnect
                connectControlChannel(server);
github microsoft / BotBuilder-Samples / Node / core-DirectLineWebSockets / DirectLineClient / app.js View on Github external
function startReceivingW3CWebSocketClient(streamUrl, conversationId) {
    console.log('Starting W3C WebSocket Client for message streaming on conversationId: ' + conversationId);

    var ws = new (require('websocket').w3cwebsocket)(streamUrl);

    ws.onerror = function () {
        console.log('Connection Error');
    };

    ws.onopen = function () {
        console.log('W3C WebSocket Client Connected');
    };

    ws.onclose = function () {
        console.log('W3C WebSocket Client Disconnected');
    };

    ws.onmessage = function (e) {
        // Occasionally, the Direct Line service sends an empty message as a liveness ping
        // Ignore these messages
github MCS-Lite / mcs-lite / packages / mcs-lite-connect / src / connectSocket.js View on Github external
this.viewer = new W3CWebSocket(`${URL}/viewer`);
        this.viewer.onopen = () =>
          this.setState(setReadyState('viewer', this.viewer));
        this.viewer.onclose = () => {
          if (this.isComponentUnmount) return;
          this.setState(setReadyState('viewer', this.viewer));
        };
        this.viewer.onmessage = payload => {
          const data = JSON.parse(payload.data);
          onMessage(this.props)(data); // Remind: Handle receieve messages.
        };
        this.viewer.onerror = error => console.info('viewer onerror', error);
      }

      if (!this.sender || this.sender.readyState >= CLOSING) {
        this.sender = new W3CWebSocket(`${URL}`);
        this.sender.onopen = () => {
          this.setState({ send: this.sender.send.bind(this.sender) });
          this.setState(setReadyState('sender', this.sender));
        };
        this.viewer.onclose = () => {
          if (this.isComponentUnmount) return;
          this.setState(setReadyState('sender', this.sender));
        };
        this.sender.onmessage = e => console.info('sender onmessage', e.data);
        this.sender.onerror = error => console.info('sender onerror', error);
      }
    };
github FE-Kits / Holo-Web / server / modules / websocket-compat.js View on Github external
options.httpServer.on('upgrade', function(req, socket, head) {
    if (typeof req.headers['sec-websocket-version'] !== 'undefined') {

      // WebSocket hybi-08/-09/-10 connection (WebSocket-Node)
      wsRequest = new WebSocketRequest(socket, req, wsServerConfig);
      try {
        wsRequest.readHandshake();
      } catch (e) {
        wsRequest.reject(
          e.httpCode ? e.httpCode : 400,
          e.message,
          e.headers
        );
        return;
      }
      wsRequest.once('requestAccepted', function(connection) {
        wsRequest.handleRequestAccepted(connection);
      });
      self.emit('request', wsRequest);

    } else {
github soundanalogous / Breakout / server / server_old.js View on Github external
httpServer.on('upgrade', function(req, socket, head) {

    if (typeof req.headers['sec-websocket-version'] !== 'undefined') {

        // WebSocket hybi-08/-09/-10 connection (WebSocket-Node)
        var wsRequest = new WebSocketRequest(socket, req, wsServerConfig);
        try {
            wsRequest.readHandshake();
            var wsConnection = wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
            handleConnection(wsConnection);
        }
        catch(e) {
            console.log("WebSocket Request unsupported by WebSocket-Node: " + e.toString());
            return;
        }

    } else {

        // WebSocket hixie-75/-76/hybi-00 connection (node-websocket-server)
        if (req.method === 'GET' &&
            (req.headers.upgrade && req.headers.connection) &&
            req.headers.upgrade.toLowerCase() === 'websocket' &&
github Daniel-Hwang / web-tunnel / nodejs-websocket-server / server.js View on Github external
next();
        }));
    });
});

app.listen(cfg.port, '0.0.0.0');

var wsServer = new WebSocketServer({
    httpServer: app,

    // Firefox 7 alpha has a bug that drops the
    // connection on large fragmented messages
    fragmentOutgoingMessages: false
});

var router = new WebSocketRouter();
router.attachServer(wsServer);

function originIsAllowed(url) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

/*
wsServer.on('request', function(request) {
    var url = request.httpRequest.url;
    if (!originIsAllowed(url)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }