šŸš€ Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more →
Socket
Sign inDemoInstall
Socket

cws

Package Overview
Dependencies
Maintainers
0
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cws

Cross-platform websockets

2.0.1
latest
Source
npm
Version published
Weekly downloads
1.2K
3.42%
Maintainers
0
Weekly downloads
Ā 
Created
Source

cws

Cross-platform interface for websockets

Install

npm install --save cws

API

For node usage, look at the ws package as that's what's returned.

src/browser.js can either be loaded directly or you can require the module through browserify. Creating a server is not supported in the browser. Arguments to the constructor are passed directly to WebSocket & this module wraps around it to provide a node-style api.

Browser

const CWS = require('cws');
// or use window.CWS

// Connect to a server
const ws = CWS('ws://server/path', /* protocols, */ options);

// Checking the current state
console.log('readyState:', ws.readyState);

// Pass errors to the console
ws.on('error', e => {
  console.error(e);
});

// Notify console of closure
ws.on('close', e => {
  console.log('The websocket was closed');
});

// Listen for messages & log them
ws.on('message', message => {
  if ('string' !== typeof message) throw Error("Message could not be decoded");
  const received = JSON.parse(message);
  console.log('Message received:', received);
});

// Wait for the socket to open
ws.on('open', () => {

  // Say hi
  ws.send(JSON.stringify({
    type: 'Greeting',
    data: 'Hello World',
  });

  // Close the socket after 5 seconds
  setTimeout(() => {
    ws.close();
  }, 5000);
});

FAQs

Package last updated on 21 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts