Skip to content

Websocket

@gaman/websocket is the official plugin dedicated to GamanJS. This plugin is built on top of the ws library.

GamanJS is a framework for backend applications, you can install using your favorite package manager:

Terminal window
npm install @gaman/websocket ws

Upgrade your HTTP server with @gaman/websocket here’s how:

index.ts
import { WebsocketGateway } from "@gaman/websocket"
defineBootstrap(async (app) => {
const server = await app.mountServer(':3431').
WebsocketGateway.upgrade(server); // upgrade your http
});

Now create your websocket handler using composeWebsocket()

ChatWebsocket.ts
import { composeWebsocket } from "@gaman/websocket"
export default composeWebsocket((event) => {
Log.info('Client joined: ' + event.clientId);
event.onMessage((msg) => {
event.send('your message: ' + msg);
})
})

Now add the ChatWebsocket.ts to the route you want

AppRoutes.ts
import { ChatWebsocket } from ".";
export default autoComposeRoutes((route) => {
route.ws('/chat', ChatWebsocket);
});

Then connect to ws://localhost:3431/chat

If you are using wscat, use this command wscat -c ws://localhost:3431/chat then type a message and enter

Here is an example of accessing GamanJS websocket from the client side

<script>
const socket = new WebSocket('ws://localhost:3431/chat')
socket.onmessage = (event) => {
console.log(event.data) // output: 'Client joined: 21515151-client-id'
}
</script>