x-platform-ws

A cross-platform wrapper over ws and WebSocket

Usage no npm install needed!

<script type="module">
  import xPlatformWs from 'https://cdn.skypack.dev/x-platform-ws';
</script>

README

x-platform-ws

The cross-platform WebSocket wrapper in Javascript, imitating the API of the ws package on browser.

Installation

First make sure you have node and npm (Comes with Node) installed, then run:

  $ npm install x-platform-ws --save

Bingo! You're made it!

Further information

If you are x-platform-ws in a project with browserify or webpack, everything will be working fine.

If not, you should add events and buffer to your dependencies. They are peer dependencies of x-platform-ws so you have to install them manually. (Webpack and browserify have them installed and automatically bundled for browsers)

Usage

  const WebSocket = require('x-platform-ws');
  const ws = new WebSocket('wss://echo.websocket.org');
  ws.on('message', data => console.log(data));
  ws.on('open', () => console.log('Opened!'));
  ws.on('close', (code, reason) => console.log(`Closed: code=${code}, reason=${reason}`));
  setTimeout(() => ws.close(), 10000);

It is almost compatible with the client in the ws package, with some noticable differences:

  • The options parameter of the WebSocket constructor is only effective on the node side.
  • The ping() and pong() methods are not supported in the browser. See this SO thread for explanations.
  • The UNIX domain sockets are not supported in the browser.
  • The 'fragment' binaryType is not supported on the browser.
  • The 'ping', 'pong', 'unexpected-response' and 'upgrade' events are not supported on the browser.
  • The send() method does not take advantage of the options and the callback is invoked immediately.

For the ws api, see the official docs.

Features

  • Support using 'nodebuffer' as binaryType with almost 100% compatibility. (Thanks to the buffer npm package)
  • Support using on(), once() and other methods of the Node EventEmitter class. (Thanks to the events npm package)

Development

First clone the repository:

  $ git clone https://github.com/std4453/x-platform-ws

Then, change to working dir:

  $ cd x-platform-ws

And:

  $ npm install

Now play with it as you like!

Versioning

We use semantic versioning for versioning. For the versions available, see the tags on this repository.

Authors

License

This project is licensed under the MIT License, see LICENSE for details.