https://github.com/idiocc/websocket
Establishes WebSocket Connetion Between Client And Server.
https://github.com/idiocc/websocket
Last synced: about 1 year ago
JSON representation
Establishes WebSocket Connetion Between Client And Server.
- Host: GitHub
- URL: https://github.com/idiocc/websocket
- Owner: idiocc
- License: mit
- Created: 2019-01-29T18:39:50.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2020-02-28T21:10:07.000Z (over 6 years ago)
- Last Synced: 2025-03-16T12:48:13.685Z (over 1 year ago)
- Language: JavaScript
- Homepage: https://idio.cc
- Size: 59.6 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# @idio/websocket
[](https://www.npmjs.com/package/@idio/websocket)
`@idio/websocket` Establishes _WebSocket_ Connections Between Clients And The Server.
```sh
yarn add @idio/websocket
npm i @idio/websocket
```
## Table Of Contents
- [Table Of Contents](#table-of-contents)
- [API](#api)
- [`websocket(server, config=): !Object`](#websocketserver-httpserverconfig-websocketconfig-objectstring-sendmessage)
* [`WebSocketConfig`](#type-websocketconfig)
- [`sendMessage(event, message): void`](#sendmessageevent-stringmessage--void)
- [Copyright](#copyright)
## API
The package is available by importing its default function:
```js
import websocket from '@idio/websocket'
```
## websocket(
`server: !http.Server,`
`config=: !WebSocketConfig,`
): !Object
Sets up a listener for the `UPGRADE` event on the server, and stores all connected clients in the client list. When clients disconnect, they are removed from this list. The list is a hash object where each key is the _accept key_ sent by the client, and values are the callback functions to send messages to those clients.
- server*
!http.Server: The server on which to setup the listener.
- config !WebSocketConfig (optional): Additional configuration.
__`WebSocketConfig`__: Options for the web socket protocol communication.
| Name | Type | Description | Default |
| --------- | ---------------------------------------------------- | ------------------------------------------------------ | ------- |
| log | boolean | Whether to log on connect and disconnect. | `true` |
| onMessage | (clientID: string, message: string) => void | The callback when a message is received from a client. | - |
| onConnect | (clientID: string) => void | The callback when a client is connected. | - |
_With the following client-side implementation:_
```js
/* eslint-env browser */
const ws = new WebSocket(`ws://${location.host}`, 'json')
setInterval(() => {
if (ws.readyState == ws.OPEN) ws.send('')
}, 2000)
ws.addEventListener('message', async event => {
const { message, event: e } = JSON.parse(event.data)
console.log('Received %s:', e, message)
window.WSstatus.innerText = message
ws.send(navigator.userAgent)
})
```
_the server can be setup to listen for connections._
```jsx
/* yarn example/ */
import core, { render } from '@idio/idio'
import websocket from '@idio/websocket'
(async () => {
const { url, server } = await core({
static: {
use: true,
root: 'example/frontend',
},
index(ctx) {
ctx.body = render(
Websocket Example
Hello World.
Server says:
, { addDoctype: true })
},
})
const clients = websocket(server, {
onConnect(clientId) {
clients[clientId]('handshake', 'welcome')
},
onMessage(clientId, message) {
console.log('Client %s says: %s', clientId, message)
},
})
console.log(url)
})()
```
```fs
http://localhost:5000
Client connected.
Client FIM/Jvt9Ldb1J0HCx5ye8g== says:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/71.0.3578.98 Safari/537.36
Client disconnected.
```
## sendMessage(
`event: string,`
`message: *,`
): void
- event* `string`: The name of the event to send.
- message* `*`: The data, that will be serialised in _JSON_.
## Copyright
WebSocket Node.JS implementation by **Srushtika Neelakantam** from [Implementing a WebSocket server with Node.js](https://hackernoon.com/implementing-a-websocket-server-with-node-js-d9b78ec5ffa8)