elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
10.26k stars 219 forks source link

WebSocket close #478

Open nodirbekrajaboff opened 8 months ago

nodirbekrajaboff commented 8 months ago

What version of Elysia.JS is running?

latest

What platform is your computer?

Linux 6.5.0-17-generic x86_64 x86_64

What steps can reproduce the bug?

When a user leaves the network, I want to notify other users that this user has left. But ws.publish() method is not working inside close(). My codes: import { html } from "@elysiajs/html"; import { Elysia, t } from "elysia";

let users: any[] = [];

const supportSocket = new Elysia({ websocket: { idleTimeout: 60, }, }) .use(html()) .get("/chat", async ({ html }) => Bun.file("./public/pages/support/chat.html") ) .ws("/chat/ws", { body: t.Object({ message: t.String({ error: "String error", }), }), open(ws) { const userId = user-${ws.id}; users.push(ws.id); ws.subscribe("chat-room"); ws.send({ type: "USER_ID", message: Your ID: ${userId}, }); ws.publish( "chat-room", JSON.stringify({ type: "JOINED_USER", message: ${userId} joined, }) ); }, message(ws, { message }) { ws.publish( "chat-room", JSON.stringify({ type: "SEND_MESSAGE", message, }) ); }, close(ws) { console.log(ws.id); ws.publish( "chat-room", JSON.stringify({ type: "LEFT_USER", message: ${ws.id} user left, }) ); }, });

export default supportSocket;

What is the expected behavior?

No response

What do you see instead?

No response

Additional information

No response

Kusigeri commented 8 months ago

The closed websocket, which cannot be used to send or publish events in the first place. The server must send the event. Check this out:

https://github.com/elysiajs/elysia/issues/359

Kusigeri commented 8 months ago

index.ts

import { Elysia } from "elysia";
import { ws } from './websocket.ts'

export const app = new Elysia()
  .onStart((app) =>  console.log(`Runing: ${app.server?.url}`))
  .use(ws)
  .listen(3000);

websocket.ts

import {app} from './index.ts'

const ws = new Elysia()
    .ws('/ws', {
        close(ws, code, message) {
               app.server?.publish('chat-room', `${ws.id} left room`)
        }
 })