简体   繁体   中英

websocket push message programmatically using java code

java 8 Spring 5 mvc Websocket handler.

how do it push websocket message programmatically(using javacode) to the client ?

I followed following example.

http://boraji.com/spring-mvc-5-handling-websocket-message-example

which creates TextWebsocketHandler .

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

   @Override
   protected void handleTextMessage(WebSocketSession session, TextMessage message)
         throws Exception {

      String clientMessage = message.getPayload();

      if (clientMessage.startsWith("Hello") || clientMessage.startsWith("Hi")) {
         session.sendMessage(new TextMessage("Hello! What can i do for you?"));
      } else {
         session.sendMessage(
               new TextMessage("This is a simple hello world example of using Spring WebSocket."));
      }
   }
}

and then pass it to websocket configurere

@Configuration
@EnableWebSocket
@ComponentScan("com.boraji.tutorial.spring.websocket")
public class WebSocketConfig implements WebSocketConfigurer {

   @Autowired
   private MyWebSocketHandler myWebSocketHandler;

   @Override
   public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(myWebSocketHandler, "/socketHandler");
   }

}

Just save your WebSocketSession somewhere in your code, and then call sendMessage(TextMessage m) on it when ever you want to send something back to the client.

For example you can save the WebSocketSession Reference when OnOpen method is called in your handler. The reference is passed as a parameter.

But anyways, your code is just doing it at:

session.sendMessage(
           new TextMessage("This is a simple hello world example of using Spring WebSocket."));

and at

session.sendMessage(new TextMessage("Hello! What can i do for you?"));

What do you mean by programmatically? you could for example create a protocol for yourself and how you handle the messages.

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