# websocket-demux

> This simple library handles the demultiplexing of requests/responces over a single websocket connection (or not)

Latest version **1.0.0** (published 2020-10-25) · MIT license · 0 weekly downloads

## Install

```sh
npm install websocket-demux
pnpm add websocket-demux
yarn add websocket-demux
bun add websocket-demux
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.0 |
| Published | 2020-10-25 |
| First published | 2020-10-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 3.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 3 |
| Author | Harry Kalogirou |
| Maintainers | harkal |

## Links

- npm: https://www.npmjs.com/package/websocket-demux
- Repository: https://github.com/harkal/websocket-demux
- Homepage: https://github.com/harkal/websocket-demux#readme
- Issues: https://github.com/harkal/websocket-demux/issues
- npm.io page: https://npm.io/package/websocket-demux

## Recent versions

- 1.0.0 (latest) — 2020-10-25

## README

Websocket Demultiplexer
=======================

This simple library handles the demultiplexing of requests/responces over a single websocket connection (or not).

The only prerequisite for the server is to be able to mark respoinces with a context value so the matchmaking can be performed. 

Usage
---

Below is an example code of how this can be used:

```javascript
const demux = require('websocket-demux')
const WebSocket = require('ws')

demux.init()

const ws = new WebSocket('wss://echo.websocket.org/', {
  origin: 'https://websocket.org'
})

ws.on('open', function open() {
  console.log('connected')
  demux.request(ws, { time: Date.now() }, (err, res)=>{
    if(err) {
      console.log('Error: ', err)
      return
    }

    console.log('Roundtrip: ', Date.now() - res.time)
  })
})

ws.on('close', function close() {
  console.log('disconnected')
  demux.socket_closed()
})

ws.on('message', function incoming(data) {
  if(demux.process_message(JSON.parse(data))){
    // The message was handled return
    return
  }

  // Do custom handling. Here we just print the message
  console.log(data)
})
```

There is also a promisified version that you can use if you fancy:

```javascript
let res = await demux.request_async(ws, { time: Date.now() })
console.log(res)
```

Installation
---
```
npm install --save websocket-demux
```

---
_Source: https://npm.io/package/websocket-demux · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
