最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - fastifywebsockets v11.0.2 and fastify v5.2.1 wont work - Stack Overflow

programmeradmin0浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论