fastify / fastify-websocket

basic websocket support for fastify
MIT License
393 stars 72 forks source link

connection.socket.on('open') doesn't work #230

Closed Gianthard-cyh closed 1 year ago

Gianthard-cyh commented 1 year ago

Prerequisites

Fastify version

4.10.0

Plugin version

7.1.1

Node.js version

19.1.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

ubuntu 20.04

Description

image

test.js


const fastify = require('fastify')({ logger: false })
fastify.register(require('@fastify/websocket'))
fastify.register(async function (fastify) {
  fastify.get('/', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
    connection.socket.on('open', () => {
      console.log('connected')
    })
    connection.socket.on('message', () => {
      console.log('message')
    })
    connection.socket.on('close', () => {
      console.log('close')
    })
  })
})

fastify.listen({ port: 3035, host: '0.0.0.0' }, err => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

I've tried postman and my browser to create ws connection but none works. message and close events are properly handled, but open is not.

Steps to Reproduce


const fastify = require('fastify')({ logger: false })
fastify.register(require('@fastify/websocket'))
fastify.register(async function (fastify) {
  fastify.get('/', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
    connection.socket.on('open', () => {
      console.log('connected')
    })
    connection.socket.on('message', () => {
      console.log('message')
    })
    connection.socket.on('close', () => {
      console.log('close')
    })
  })
})

fastify.listen({ port: 3035, host: '0.0.0.0' }, err => {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

Expected Behavior

No response

jsumners commented 1 year ago

The docs https://github.com/fastify/fastify-websocket/blob/1e41ac4aa3ce21a69e6718977509fee8c5d0f22e/README.md do not mention an open event. They only mention a message event.

Gianthard-cyh commented 1 year ago

The docs https://github.com/fastify/fastify-websocket/blob/1e41ac4aa3ce21a69e6718977509fee8c5d0f22e/README.md do not mention an open event. They only mention a message event.

so how can i do if i want to send a message immediately after the connection is open?

airhorns commented 1 year ago

You can just send right in the request handler!

fastify.get('/', { websocket: true }, (connection /* SocketStream */, req /* FastifyRequest */) => {
    connection.socket.send("synchronous message on connection open")
  })
climba03003 commented 1 year ago

When you reach the handler, it is already open. @fastify/websocket is server side, once it reach. It means the connection already there.