简体   繁体   中英

Spring Websocket Handler not publishing message to all clients

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM