好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot使用WebSocket实现前后端交互的操作方法

背景

我们都知道http协议只能在浏览器单方面向服务器发起请求时获得响应,然而服务器不能主动向浏览器推送消息,想要实现浏览器的主动推送目前有两种主流的实现方式:

轮询:缺点很多,但是实现简单 websocket: 在浏览器和服务器之间建立TCP连接,实现全双工通信 springboot使用websocket有两种方式,一种是实现简单的websocket,另外一种是实现STOMP协议。本篇讲述如何使用springboot实现简单的websocket。

实现

一、导入依赖

直接在 pom.xml 中导入依赖。

?

1

2

3

4

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-websocket</artifactId>

</dependency>

二、新建WebSocket配置类,注入Bean

首先注入一个ServerEndpointExporterBean,该Bean会自动注册使用@ServerEndpoint注解申请的websocket endpoint,代码如下:

?

1

2

3

4

5

6

7

@Component

public class WebSocketConfig {

     @Bean

     public ServerEndpointExporter serverEndpointExporter(){

         return new ServerEndpointExporter();

     }

}

三、新建WebSocket服务端,在其中处理websocket逻辑

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

@Component   //注册到容器中

@ServerEndpoint ( "/webSocket" )  //接收websocket请求路径

@Slf4j

public class WebSocket {

     //当前连接(每个websocket连入都会创建一个WebSocket实例)

     private Session session;

     //定义一个websocket容器存储session,即存放所有在线的socket连接

     private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

     //处理连接建立

     @OnOpen

     public void opOpen(Session session){

         this .session = session;

         log.info( "【有新的客户端连接了】:{}" ,session.getId());

         webSocketSet.add( this );  //将新用户加入在线组

         log.info( "【websocket消息】有新的连接,总数:{}" ,webSocketSet.size());

     }

     //处理连接关闭

     @OnClose

     public void Onclose(){

         webSocketSet.remove( this );

         log.info( "【websocket消息】连接断开,总数:{}" ,webSocketSet.size());

     //接受消息

     @OnMessage

     public void onMessage(String message){

         log.info( "【websocket消息】收到客户端发来的消息:{}" ,message);

     // 群发消息

     public void sendMessage(String message) {

         for (WebSocket webSocket : webSocketSet) {

             log.info( "【websocket消息】广播群发消息,message={}" ,message);

             try {

                 webSocket.session.getBasicRemote().sendText(message);

             } catch (Exception e){

                 e.printStackTrace();

             }

         }

}

四、客户端实现,可以借助FreeMarker模板工具直接写在ftl文件里。

由于部分浏览器可能不支持,可以先测试,代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<script>

     var websocket = null ;

     if ( 'WebSocket' in window){

         websocket = new WebSocket( 'ws://localhost:8080/webSocket' );

     } else {

         alert( '当前浏览器不支持websocket消息通知' );

     }

     //连接成功建立的回调方法

     websocket.onopen = function (event) {

         console.log( "ws建立连接成功" );

     //连接关闭的回调方法

     websocket.onclose = function (event) {

         console.log( "ws连接关闭" );

     //接收到消息的回调方法

     websocket.onmessage = function (event) {

         /*setMessageInnerHTML(event.data);*/

        // alert("ws接收返回消息:"+event.data);

         console.log( "服务器返回消息: " + event.data);

         //弹窗提醒(要用到JQuary,所以要先引入JQuary)   播放音乐

         $( '#mymodal' ).modal( 'show' )

     //连接发生错误的回调方法

     websocket.onerror = function(event){

         alert( 'websocket通信发生错误!' )

     //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。

     window.onbeforeunload = function() {

         websocket.close();

     </script>

五、测试

(项目实现客户创建新订单之后,前台发出提醒)

?

1

2

3

4

5

6

7

8

9

10

@Autowired

private WebSocket webSocket;

@Override

     @Transactional

     public OrderDTO create(OrderDTO orderDTO) { //创建订单

         。。。。(具体代码省略)

        //创建新订单  发送websocket消息

         webSocket.sendMessage(orderDTO.getOrderId());

         return orderDTO;

     }

添加新订单:

接收到websocket消息

到此这篇关于SpringBoot使用WebSocket实现前后端交互的操作方法的文章就介绍到这了,更多相关SpringBoot前后端交互内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://www.cnblogs.com/xiaozhengtongxue/p/13448778.html

查看更多关于SpringBoot使用WebSocket实现前后端交互的操作方法的详细内容...

  阅读:19次