Websocket
@gaman/websocket is the official plugin dedicated to GamanJS. This plugin is built on top of the ws library.
install
Section titled “install”GamanJS is a framework for backend applications, you can install using your favorite package manager:
npm install @gaman/websocket wspnpm install @gaman/websocket wsyarn install @gaman/websocket wsbun install @gaman/websocket wsUpgrade your HTTP server with @gaman/websocket here’s how:
import { WebsocketGateway } from "@gaman/websocket"
defineBootstrap(async (app) => { const server = await app.mountServer(':3431'). WebsocketGateway.upgrade(server); // upgrade your http});Websocket Handler
Section titled “Websocket Handler”Now create your websocket handler using composeWebsocket()
import { composeWebsocket } from "@gaman/websocket"
export default composeWebsocket((event) => { Log.info('Client joined: ' + event.clientId); event.onMessage((msg) => { event.send('your message: ' + msg); })})Add to Route
Section titled “Add to Route”Now add the ChatWebsocket.ts to the route you want
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
Client Side
Section titled “Client Side”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>