Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to broadcast messages in Spring Reactive Websocket API?

I'm developing a simple chat. I really like the Tomcat based spring websocket API, but there is one problem. Tomcat uses a thread-based model. If I have around 500 online users, tomcat starts 200 threads (default value) and my CPU dies. Therefore, I need a websocket implementation which is event-loop based. I decided to try the brand-new spring reactive API with websockets.

So, I need a chat with chat rooms. When some user sends a message within a chat room, must be sent to all users in the chat room.

Spring offers the following API:

@Service
public class ChatWebSocketHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        Mono<Void> input =  ;
        Mono<Void> output = ;

        return Mono.zip(input, output).then();
    }
}

There is no API for detecting connected and disconnected events (like, it was with Tomcat). So, I cannot store a collection of active sessions, which can be used for message broadcasting.

like image 256
Max Avatar asked Mar 04 '23 10:03

Max


1 Answers

There is a good article which covers the implementation of a global chat application using webflux in combination with websockets how-to-build-a-chat-app-using-webflux-websockets-react. You should be able to get a grasp of the API through his code and to modify it to support your needs of multiple chat rooms.

He also describes how you can listen for connect and disconnect "events". You can find the corresponding project on github: java-reactive-chat.

like image 107
FlorianDe Avatar answered Mar 09 '23 00:03

FlorianDe