honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
20.38k stars 584 forks source link

Cloudflare Workers `onOpen` WebSocket event is not triggered #3448

Closed imLymei closed 1 month ago

imLymei commented 1 month ago

What version of Hono are you using?

4.6.3

What runtime/platform is your app running on?

Cloudflare Workers

What steps can reproduce the bug?

The onOpen websocket event is not called

steps:

  1. npm create hono@4.6.3
  2. Select cloudflare workers
  3. paste code:
    
    import { Hono } from 'hono';
    import { upgradeWebSocket } from 'hono/cloudflare-workers';

const websocketClients: WebSocket[] = [];

const app = new Hono();

app.get( '/ws', upgradeWebSocket((c) => { console.log('WebSocket upgrade requested');

return {
  onOpen(event, ws) {
    console.log('WebSocket connection opened');
    websocketClients.push(ws.raw!);
  },
  onError(evt, ws) {
    console.error('WebSocket error:', evt);
  },
  onMessage(event, ws) {
    console.log(`Message from client: ${event.data}`);
    websocketClients.forEach((client) => {
      if (client !== ws.raw) {
        client.send(event.data + ' ' + JSON.stringify(websocketClients));
      }
    });
  },
  onClose: (_, ws) => {
    console.log('WebSocket connection closed');
    const index = websocketClients.indexOf(ws.raw!);
    if (index > -1) {
      websocketClients.splice(index, 1);
    }
  },
};

}) );

export default app;



### What is the expected behavior?

console to print "`WebSocket connection opened`"

### What do you see instead?

no "`WebSocket connection opened`"

![image](https://github.com/user-attachments/assets/1c6c17ad-7216-4a65-a615-1fdbf34a3cf7)

### Additional information

_No response_
yusukebe commented 1 month ago

Hi @imLymei

If I remember correctly, Cloudflare Workers does not support the open. For instance, the open is not listed the below doc:

https://developers.cloudflare.com/workers/runtime-apis/websockets/#events

Hey @naporin0624 Is it right?

imLymei commented 1 month ago

Well, that sucks. Thank you for clarifying things up!