websocket issue
import { Hono } from 'hono';
import { createBunWebSocket } from 'hono/bun';
import type { WSContext, WSEvents, WSMessageReceive } from "hono/ws";
const { upgradeWebSocket, websocket } = createBunWebSocket();
const app = new Hono();
type Message = {
room: string;
user: string;
text: string;
timestamp: string;
};
const chatClients: { [room: string]: { clients: WSContext[], messages: Message[] } } = {};
app.get(
'/ws',
upgradeWebSocket((c) => {
let room: string;
let clients: WSContext[] = [];
let messages: Message[] = [];
return {
onOpen(event, ws) {
room = c.req.query('room');
if (!room) {
ws.close();
return;
}
if (!chatClients[room]) {
chatClients[room] = { clients: [], messages: [] };
}
({ clients, messages } = chatClients[room]);
clients.push(ws);
},
onMessage(event) {
const msg: Message = JSON.parse(${event.data});
msg.timestamp = new Date().toISOString();
messages.push(msg);
clients.forEach(client => {
client.send(JSON.stringify(msg));
});
},
onClose(event, ws) {
const index = clients.indexOf(ws);
if (index !== -1) {
clients.splice(index, 1);
}
},
};
})
);
app.get('/api/messages/:room', (c) => {
const room = c.req.param('room');
const messages = chatClients[room]?.messages || [];
return c.json(messages);
});
Bun.serve({
fetch: app.fetch,
port: 3001,
websocket,
});import { Hono } from 'hono';
import { createBunWebSocket } from 'hono/bun';
import type { WSContext, WSEvents, WSMessageReceive } from "hono/ws";
const { upgradeWebSocket, websocket } = createBunWebSocket();
const app = new Hono();
type Message = {
room: string;
user: string;
text: string;
timestamp: string;
};
const chatClients: { [room: string]: { clients: WSContext[], messages: Message[] } } = {};
app.get(
'/ws',
upgradeWebSocket((c) => {
let room: string;
let clients: WSContext[] = [];
let messages: Message[] = [];
return {
onOpen(event, ws) {
room = c.req.query('room');
if (!room) {
ws.close();
return;
}
if (!chatClients[room]) {
chatClients[room] = { clients: [], messages: [] };
}
({ clients, messages } = chatClients[room]);
clients.push(ws);
},
onMessage(event) {
const msg: Message = JSON.parse(${event.data});
msg.timestamp = new Date().toISOString();
messages.push(msg);
clients.forEach(client => {
client.send(JSON.stringify(msg));
});
},
onClose(event, ws) {
const index = clients.indexOf(ws);
if (index !== -1) {
clients.splice(index, 1);
}
},
};
})
);
app.get('/api/messages/:room', (c) => {
const room = c.req.param('room');
const messages = chatClients[room]?.messages || [];
return c.json(messages);
});
Bun.serve({
fetch: app.fetch,
port: 3001,
websocket,
});in this example, the onClose wont work, because the ws isnt the same object as in the array, how do i even identify the the websocket to remove from the array



