Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/harkal/websocket-demux
Demultiplexes messages over a websocket in a straitforward request handling fashion
https://github.com/harkal/websocket-demux
Last synced: 8 days ago
JSON representation
Demultiplexes messages over a websocket in a straitforward request handling fashion
- Host: GitHub
- URL: https://github.com/harkal/websocket-demux
- Owner: harkal
- Created: 2020-10-24T21:51:22.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2020-10-25T10:11:17.000Z (about 4 years ago)
- Last Synced: 2024-10-07T21:41:13.374Z (30 days ago)
- Language: JavaScript
- Size: 1.95 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
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
```