简体   繁体   English

使用Java代码以编程方式将websocket推送消息

[英]websocket push message programmatically using java code

java 8 Spring 5 mvc Websocket handler. java 8 Spring 5 mvc Websocket处理程序。

how do it push websocket message programmatically(using javacode) to the client ? 它如何以编程方式(使用javacode)将websocket消息推送到客户端?

I followed following example. 我遵循以下示例。

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

which creates TextWebsocketHandler . 创建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 然后将其传递给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. 只需将WebSocketSession保存在代码中的某个位置,然后在想将任何内容发送回客户端时调用sendMessage(TextMessage m)

For example you can save the WebSocketSession Reference when OnOpen method is called in your handler. 例如,当在处理程序中调用OnOpen方法时,您可以保存WebSocketSession引用。 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. 例如,您可以为自己创建协议以及如何处理消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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