Skip to content

small and lightweight client (browser) & server (nodejs) websocket handlers in javascript

License

Notifications You must be signed in to change notification settings

Aelto/ws-handler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ws-handler

Two classes for a small and simple client/server websocket communication. They are made to work with each other, this means if you use ws-client alone it won't always perfectly. Note that the server class uses express-ws api.

Client helper

Websocket client class located at:

Simple usage example

the code has been skimmed to keep it focused on what matter: the classes. complete example can be found at /example/index.html

import WsClient from './ws-client.js'

const client = new WsClient()

client
.on('new-message-done', ({ message }) => addMessage(message.text))
.open()

const sendNewMessage = text =>
  client.send('new-message', { text })

// ...

API

Constructor()

instantiate a new Websocket client

const client = new WsClient()

on(title: string, fn: ({ message: { [string]: any } }) => void)

Set an event listener that will be called everytime an incoming object has the same title as the supplied one.

client.on('event', { message } => console.log(message.myEventText))

onAnswer(title: string, fn: ({ message: { [string]: any } }) => void)

Exactly the same as the on method, but appends -done at title. this is because the server class also appends -done to any event he answers, it's a way to know when the server pushes an event and when he answers to an event.

client.onAnswer('event', { message } => console.log(message.myEventText))

emit(title: string, obj: { message: { [string]: any } })

This is an internal method that is public as it can be useful when someone wants to manually trigger events. title is the event's name and obj is the data passed to the event function.

client.emit('event', { message: { myEventText: 'hello' } })

note that the myEventText key can be whatever you want

addOnClose(fn: () => void)

Add a function that will be called once the websocket connection is closed.

client.addonClose(() => alert('websocket connection lost'))

send(title: string, message: { [string]: any }, thenableId: number | undefined)

Send a message with the current websocket connection where title is the event name to trigger on the server side, message is the data sent to the server

client.send('add-user', { username: 'user_1' })

generateNewId(): number

Internal method set to public just in case someone wants to generate a number between 0 and 100.

hasThenable(id: number): boolean

Returns true if a promise linked to the given id is waiting for its resolution.

consumeThenable(id: number, data = null: { [string]: any })

Resolve the stored thenable promise by passing it the supplied data then delete it.

client.consumeThenable(0, { username: 'user_1' })

thenable(title: string, message: { [string]: any }): Promise

Send the supplied data with the given event title. This method returns a promise that is resolved once the server answers back.

client.thenable('add-user', { username: 'user_1' })
.then({ message } => console.log(`response: ${message}`))

open(address = '${window.location.hostname}:${window.location.port}')

Open the websocket connection to the given address.

Server helper

Websocket client class located at /dist/ws-server.js

Simple usage example

the code has been skimmed to keep it focused on what matter: the classes. complete example can be found at /example/index.js

import WsServer from './ws-server.js'

// ...

const serverWs = new WsServer()
  .accept(app, '/ws')

serverWs.on('new-message', (ws, { message }) => 
  serverWs.broadcast('new-message', { text: message.text }))

// ...

API

constructor()

Instantiate a new WsServer

const serverWs = new WsServer()

on(title: string, fn: (Websocket, { message: { [string]: any } }))

Set an event listener that will be called everytime an incoming object has the same title as the supplied one.

serverWs.on('add-user', (wsClient, { message }) => {
  // ...
})

emit(name: string, obj: { message: { [key]: any } }, ws: Websocket)

This is an internal method that is public as it can be useful when someone wants to manually trigger events. title is the event's name and obj is the data passed to the event function.

serverWs.emit('add-user', { message: { username: 'user_1' } }, userWebsocket)

send(wsClient: Websocket, title: string, message: { [string]: any }, thenableId = undefined: number | undefined, state = 200: number)

Send a message with the current websocket connection where title is the event name to trigger on the client side, message is the data sent to the client

answer(wsClient: Websocket, req: { message: { [string]: any } }, message: { [string]: any }, state = 200: number)

give back an answer to the client, it uses the same title as the incoming request with -done appended to it.

serverWs.on('add-user', (wsClient, req) => {
  const { message } = req
  
  serverWs.answer(wsClient, req, { information: 'created 1 new user' })
})

broadcast(title: string, message: { [string]: any })

It has the same behavior as the send method but targets every user connected to the server

serverWs.broadcast('chat-message', { text: 'broadcast to all users' })

accept(app: Express, path: string): WsClient

Open the websocket connection using the given path, then return the current instance of WsClient so this method is chainable.

const serverWs = new WsServer()
  .accept(app, '/ws')

About

small and lightweight client (browser) & server (nodejs) websocket handlers in javascript

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages