How to use the websocket.w3cwebsocket function in websocket

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 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 signalapp / Signal-Desktop / js / modules / web_api.js View on Github external
function _createSocket(url, { certificateAuthority, proxyUrl }) {
  let requestOptions;
  if (proxyUrl) {
    requestOptions = {
      ca: certificateAuthority,
      agent: new ProxyAgent(proxyUrl),
    };
  } else {
    requestOptions = {
      ca: certificateAuthority,
    };
  }

  // eslint-disable-next-line new-cap
  return new WebSocket(url, null, null, null, requestOptions);
}
github SkygearIO / skygear-SDK-JS / packages / skygear-core / lib / pubsub.js View on Github external
* you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import _ from 'lodash';
import _ws from 'websocket';
let WebSocket = null;
if (_ws) {
  WebSocket = _ws.w3cwebsocket;
} else {
  WebSocket = window.WebSocket; //eslint-disable-line
}
import url from 'url';
import ee from 'event-emitter';

import {EventHandle} from './util';
import Container from './container'; // eslint-disable-line no-unused-vars

const ON_OPEN = 'onOpen';
const ON_CLOSE = 'onClose';

/**
 * The Pubsub client
 */
export class Pubsub {
github WangYihang / Platypus / html / frontend / src / App.js View on Github external
componentDidMount() {
    let _this = this;
    _this.fetchData();

    var client = new W3CWebSocket(wsUrl);
    client.onerror = () => {
      // message.error("WebSocket connect failed!", 5);
    };
    client.onopen = () => {
      // message.success("WebSocket connected!", 5);
    };
    client.onmessage = (e) => {
      let CLIENT_CONNECTED = 0;
      let CLIENT_DUPLICATED = 1;
      let SERVER_DUPLICATED = 2;
      let COMPILING_TERMITE = 3;
      let COMPRESSING_TERMITE = 4;
      let UPLOADING_TERMITE = 5;

      let data = JSON.parse(e.data);
github ethereum / web3.js / lib / json-rpc / providers / factories / ProvidersModuleFactory.js View on Github external
createWebsocketProvider(url, options = {}) {
        let headers = options.headers || {};

        // runtime is of type node
        if (typeof process !== 'undefined' && process.versions != null && process.versions.node != null) {
            const urlObject = new URL(url);

            if (!headers.authorization && urlObject.username && urlObject.password) {
                const authToken = Buffer.from(`${urlObject.username}:${urlObject.password}`).toString('base64');
                headers.authorization = `Basic ${authToken}`;
            }
        }

        return new WebsocketProvider(
            new W3CWebsocket(
                url,
                options.protocol,
                options.origin,
                headers,
                options.requestOptions,
                options.clientConfig
            ),
            options.timeout,
            options.reconnectDelay
        );
    }
github versatica / protoo / test / include / createApp.js View on Github external
let client;

		username = username || Math.round(100000 * Math.random()).toString();
		uuid = uuid || Math.round(100000 * Math.random()).toString();

		if (protocol === undefined)
			protocol = 'protoo';

		protocols = protocol ? [protocol] : [];

		connectUrl = url + '/?username=' + username + '&uuid=' + uuid;

		if (useWss)
			options.rejectUnauthorized = false;

		client = new W3CWebSocket(connectUrl, protocols, null, null, options);

		client.sendRequest = function(method, path, data, id)
		{
			let req =
			{
				method : method,
				id     : id || Math.round(100000 * Math.random()),
				path   : path
			};

			if (data)
				req.data = data;

			client.send(JSON.stringify(req));
		};
github run27017 / fake-messages / client / websocket.js View on Github external
function connect () {
  const client = new W3CWebSocket(url(), 'echo-protocol')

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

  client.onopen = function() {
    console.log('WebSocket Client Connected')
  }

  client.onclose = function() {
    console.log('WebSocket Client Closed')
  }

  client.onmessage = function(e) {
    console.log('Received:', e.data)
github 0xProject / 0x-monorepo / packages / connect / src / orderbook_channel_factory.ts View on Github external
return new Promise((resolve, reject) => {
            const client = new WebSocket.w3cwebsocket(url);
            client.onopen = () => {
                const orderbookChannel = new WebSocketOrderbookChannel(client, handler);
                resolve(orderbookChannel);
            };
            client.onerror = err => {
                reject(err);
            };
        });
    },
github ebu / pi-list / apps / listwebserver / worker / webSocketMonitor.js View on Github external
.then(response => {
            const ws_href = _.get(response, ['data', 'ws_href']);

            if (_.isNil(ws_href)) {
                logger('nmos-crawler').error(
                    `Unexpected response from NMOS registry when subscribing to web socket: ${response}`
                );

                return;
            }

            logger('nmos-crawler').info(`WS href: ${ws_href}`);

            const client = new W3CWebSocket(ws_href, null);

            client.onerror = err => {
                logger('nmos-crawler').error(
                    `Error connecting to Websocket: ${err}`
                );
            };

            client.onopen = () => {
                logger('nmos-crawler').info('Connected to Websocket');
            };

            client.onclose = e => {
                logger('nmos-crawler').info('Connection to Websocket closed.');
            };

            client.onmessage = e => {