I have a fastify project and i want to integrate a websocket.
According to the docs
import { FastifyInstance, FastifyPluginOptions } from 'fastify'
import websocket from '@fastify/websocket'
export default async (server: FastifyInstance, options: FastifyPluginOptions) => {
server.register(websocket)
// Define a simple WebSocket route.
server.get('/:address', { websocket: true }, (socket, req) => {
console.log('WebSocket connection established for address:', req.params['address'])
console.log(connection, req)
socket.on('message', (message: Buffer) => {
console.log('Received message:', message.toString())
// Echo a simple reply back to the client.
socket.send('Hi from server')
})
})
This should be correct.
However the "socket" object is just a normal request object.
But typescript infers it as "Websocket"
Thats why typescript does not cry, when having the code above.
import { FastifyInstance, FastifyPluginOptions } from 'fastify'
import websocket from '@fastify/websocket'
export default async (server: FastifyInstance, options: FastifyPluginOptions) => {
server.register(websocket)
// Define a simple WebSocket route.
server.get('/:address', { websocket: true }, (connection, req) => {
console.log('WebSocket connection established for address:', req.params['address'])
console.log(connection, req)
connection.socket.on('message', (message: Buffer) => {
console.log('Received message:', message.toString())
// Echo a simple reply back to the client.
connection.socket.send('Hi from server')
})
})
But this code does actually work.
And i am confused why.
Does anyone have a good example on how to use those?