温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot整合WebSocket的示例分析

发布时间:2021-06-15 16:08:51 来源:亿速云 阅读:226 作者:小新 栏目:编程语言

这篇文章主要介绍了 Spring Boot整合WebSocket的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

Spring Boot整合WebSocket

  1. 添加依赖到pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>


  2. 添加配置文件

    @Configuration
    public class WebSocketConfig {
        @Bean
        ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }


  3. 添加WebSocket的服务端

    @Component
    @ServerEndpoint("/ws/{username}")
    public class WebSocketEchoServer {
    
        @OnOpen
        public void onOpen(Session session, @PathParam("username") String username) {
            System.out.println("username = " + username + " is online.");
    
        }
    
        @OnClose
        public void onClose(Session session, @PathParam("username") String username, CloseReason closeReason) {
            System.out.println("username = " + username + " is offline.");
            System.out.println("Closing a WebSocket due to " + closeReason.getReasonPhrase());
        }
    
        // @OnMessage
        // public String onMessage(String message, Session session) throws IOException {
        //     System.out.println("received message=" + message);
        //     return "echo " + message;
        // }
    
        @OnMessage
        public void onMessage(String message, Session session) throws IOException {
            System.out.println("received message=" + message);
            session.getBasicRemote().sendText("echo " + message);
        }
    
        @OnError
        public void onError (Session session, Throwable throwable) {
            System.out.println("发生错误");
            throwable.printStackTrace();
        }
    
        public void boardCast(Message message) {
            // todo: 遍历所有的session,给所有session发送消息
    
        }
    }


  4. 测试页面(WebSocket Client)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试页面</title>
        <script src="./js/jquery-1.12.3.min.js"></script>
    </head>
    <body>
    <input id="msg">
    <button id="send">发送</button>
    
    <script>
        $(document).ready(function () {
            var ws;
    
            if ('WebSocket' in window) {
                ws = new WebSocket("ws://localhost:8080/ws/tom");
    
            }
            ws.onopen = function(evt) {
                console.log("Connection open ...");
                ws.send("Hello WebSockets!");
            };
    
            ws.onmessage = function(evt) {
                console.log( "Received Message: " + evt.data);
                // ws.close();
            };
    
            ws.onclose = function(evt) {
                console.log("Connection closed.");
            };
    
            $("#send").click( function() {
                var data = {};
                data["from"] = "jack";
                data["to"] = "tom";
                data["text"] = $("#msg").val();
                ws.send(JSON.stringify(data));
            })
    
        });
    
    
    </script>
    </body>
    </html>


    这里使用一个非常简单的测试页面,只包含一个输入框和一个发送按钮。

    当我们点击按钮的时候,就把输入框中的内容,发送到服务端。

    测试页面使用的服服务端的URI是"ws://localhost:8080/ws/tom",其中“tom”对应的参数username。

常用注解说明

  • @ServerEndpoint:告诉容器将给定类视为WebSocket Server Endpoint。注解有一个必填参数value,用于指定路径。

@ServerEndpoint("/hello") 
public class MyEndpoint { }

上诉代码将发布一个相对路径是hello的Endpoint。路径可以包含在后续方法调用中使用的路径参数;例如,例如,/hello/{userid}是有效路径,{userid}的值可以在方法调用中使用@PathParam注释获得。

默认端口8080,WebSocket 可以使用如下地址访问:ws://localhost:8080/mycontextroot/hello

  • 声明当前类是WebSocket server,注解后面的字符串("/ws/{username}")指定监听的uri地址。这里“/ws/{username}”对应的完整的地址“ws://localhost:8080/ws/XXX”, XXX代表是参数username的值。

  • @ClientEndpoint: 声明当前类是WebSocket Client。

  • @OnOpen: 在连接建立后调用,方法可以包含如下参数

    • javax.websocket.Session参数

    • EndpointConfig参数,包含endpoint的配置信息

    • 0个或多个用 @PathParam注解的参数。

      @OnOpen
      public void myOnOpen (Session session) {
         System.out.println ("WebSocket opened: "+session.getId());
      }


  • @OnMessage: 接收到消息时调用,方法包含如下参数:

    • javax.websocket.Session参数

    • 0个或多个用 @PathParam注解的参数

    • 接收到的消息,默认是String类型。如果使用了编解码函数,也可以是Java Object类型。

      @OnMessage
      public void myOnMessage (String txt) {
         System.out.println ("WebSocket received message: "+txt);
      }


    • 上诉代码的返回值是void,还有一种返回值不是void的写法,这种实现会直接把返回值发送给客户端。

      @OnMessage
      public String myOnMessage (String txt) {
         return txt.toUpperCase();
      }


      还有一个发送消息的方法:

      RemoteEndpoint.Basic other = session.getBasicRemote();
      other.sendText ("Hello, world");


  • @OnClose: 连接关闭时调用,方法可以包含如下参数:

    @OnClose
    public void myOnClose (CloseReason reason) {
       System.out.prinlnt ("Closing a WebSocket due to "+reason.getReasonPhrase());
    }


    • javax.websocket.Session参数

    • javax.websocket.CloseReason参数

  • @OnError: 通讯过程中出现错误时调用

    • @OnError
      public void onError(Session session, Throwable throwable) {
          // Do error handling here
      }

感谢你能够认真阅读完这篇文章,希望小编分享的“ Spring Boot整合WebSocket的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI