0

I have a Spring Websocket server, very simple one:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(new WebsocketHandler(), "/socket").setAllowedOrigins("*");
    }
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxBinaryMessageBufferSize(1024000);
        container.setMaxTextMessageBufferSize(1024000);
        return container;
    }

}

And

public class WebsocketHandler extends AbstractWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        System.out.println(message.getPayload()+"\n");
        session.sendMessage(message);
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws IOException {
        System.out.println("New Binary Message Received");
        session.sendMessage(message);
    }
}

When I open the client which is just a simple HTML with SockJS library, the client can send receive messages from the server but if I open a new tab with the similar client it is not able to receive the messages posted by the other client.

Is this because of session.sendMessage(message);? What should be the configuration that when one client posts messages all other clients would be able to receive it?

1 Answer 1

1

if you want to send the data to other clients, you need to track sessions. As you can see in the document at this LINK the handler also has two functions for after connection is open and after the connection is closed. So how does this help you? You can keep a synchronized collection like CopyOnWriteList<T> or use Collections.Synchronized, when a client connects (afterConnectionEstablished(WebSocketSession session)), add this client to this collection or when the client disconnects ( afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) ), you can remove the session from your collection. when you want to send a message to every client, loop over this collection and use the session to send Objects. if you still find this confusing, I can provide a code sample.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.