wscl

Simple browser WebSocket wrapper with some extra features

Usage no npm install needed!

<script type="module">
  import wscl from 'https://cdn.skypack.dev/wscl';
</script>

README

wscl

NPM version

Simple browser WebSocket wrapper with some extra features:

  • auto reconnect with x2 time strategy
  • wait connection before sending message

Lib is tiny. Its size limited to 511 bytes (with all deps, minified and gzipped).

How to use

yarn add wscl
import {WSClient, WSEvents} from 'wscl'

async function test() {
  const ws = new WSClient({
    url: 'wss://echo.websocket.org',
    reconnect: true,
    reconnectWaitMin: 125,
    reconnectWaitMax: 8000,
  })
  
  ws.on(WSEvents.Open, console.log)
  ws.on(WSEvents.Close, console.log)
  ws.on(WSEvents.Message, console.log)
  ws.on(WSEvents.Error, console.log)

  // you can send message before connect
  ws.send("message")

  await ws.connect()
  console.log(ws.connected)
  
  ws.close("reason")
  
  ws.connect()
  await ws.ready
}

IE and old browsers

If you support IE and old browsers, you need to transpile wscl and nanoevents from node_modules.