> npm i @adonisjs/websocket-client
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
This guide covers the JavaScript WebSocket client used to connect to the WebSocket server.
As the WebSocket client is not installed by default, we need to pull it from npm
:
> npm i @adonisjs/websocket-client
Once installed, bundle the package using Webpack, Rollup, etc. |
Then, import the WebSocket client like so:
import Ws from '@adonisjs/websocket-client'
const ws = Ws('ws://localhost:3333')
The module build requires the regenerator-runtime polyfill (add it via Babel).
As the development build contains a number of log statements, we recommend defining NODE_ENV
via Webpack DefinePlugin or rollup-plugin-replace.
Connect to a WebSocket server via the client like so:
const ws = Ws(url, options)
// connect to the server
ws.connect()
The url parameter will fallback to the current hostname if a full ws:// url value is omitted.
|
Key | Default Value | Description |
---|---|---|
|
|
The path used to make the connection (only change if you changed it on the server). |
|
|
Whether to reconnect automatically after disconnect. |
|
|
Number of reconnection attempts before abandoning. |
|
|
How long to wait before reconnecting. The value will be used as |
|
|
Query string to pass to the connection URL (also accepts an object). |
|
|
The encoder to use (the same encoder will be required on the server). |
To manage your application state, listen for the open
/close
events:
let isConnected = false
ws.on('open', () => {
isConnected = true
})
ws.on('close', () => {
isConnected = false
})
Once connected, subscribe to different/multiple topics:
const chat = ws.subscribe('chat')
chat.on('ready', () => {
chat.emit('message', 'hello')
})
chat.on('error', (error) => {
console.log(error)
})
chat.on('close', () => {
})
The following methods are used to send/receive messages.
Remove event listener:
const messageHandler = function () {}
chat.on('message', messageHandler)
chat.off('message', messageHandler)
Initiate request to close the subscription:
chat.on('close', () => {
// server acknowledged close
})
chat.close()
Listen for the close event to confirm the subscription closed. |
Emitted when the server refuses to close the subscription:
chat.on('leaveError', (response) => {
console.log(response)
})
Emitted when an error occurs on the TCP connection:
chat.on('error', (event) => {
})
Preferably, listen for the ws.on('error') event instead.
|
The following methods are available on a single ws
connection.
Forcefully close the connection:
ws.close()
Removes all subscriptions and does not trigger a reconnection. |
Returns the subscription instance for a given topic:
ws.subscribe('chat')
ws.getSubscription('chat').on('message', () => {
})
If no subscriptions for the given topic, returns null .
|
Subscribe to a topic:
const chat = ws.subscribe('chat')
Subscribing to the same topic twice raises an exception. |
The AdonisJs WebSocket client makes it simple to authenticate users.
Auth credentials are only passed once to the server during the initial connection, so the same information can be reused to allow/disallow channel subscriptions.
If your application uses sessions, users will be authenticated automatically providing they have a valid session. |
Authenticate via basic auth:
const ws = Ws(url, options)
ws
.withBasicAuth(username, password)
.connect()
Authenticate via api token:
const ws = Ws(url, options)
ws
.withApiToken(token)
.connect()
Authenticate via JWT token:
const ws = Ws(url, options)
ws
.withJwtToken(token)
.connect()
On the server, access user information via the auth
object:
Ws.channel('chat', ({ auth }) => {
console.log(auth.user)
})
Required middleware must be set up to access the auth object.
|
To authenticate connections, ensure the auth
named middleware is applied:
Ws.channel('chat', ({ auth }) => {
console.log(auth.user)
}).middleware(['auth'])