Springboot 使用 webSocket

 介绍

WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。WebSocket使用和 HTTP 相同的 TCP 端口,可以绕过大多数防火墙的限制。默认情况下,WebSocket协议使用80端口;运行在TLS之上时,默认使用443端口。
WebSocket协议建立连接的时候需要握手,握手过程中需要借助HTTP协议来完成,当连接建立后,就可以使用WebSocket协议进行通信,通信结束后,通信双方都可以关闭连接。

 API文档:https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket

前端:

1、新建服务器的连接:var webSocket = new WebSocket(url);
2、初始化回调函数
ex:webSocket.onmessage = function (event){
var data = event.data;
console.log(“收到的消息”+data);
}

 

3、发送消息给服务器
webSocket.send(message);

 

 

后端:

  • 配置pom文件
   <!-- 引入 websocket 依赖类-->
         <dependency>
           <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

开启WebSocket服务端的自动注册
注意:ServerEndpointExporter 是由Spring官方提供的标准实现,用于扫描ServerEndpointConfig配置类和@ServerEndpoint注解实例。使用规则也很简单:1.如果使用默认的嵌入式容器 比如Tomcat 则必须手工在上下文提供ServerEndpointExporter。2. 如果使用外部容器部署war包,则不要提供提供ServerEndpointExporter,因为此时SpringBoot默认将扫描服务端的行为交给外部容器处理
 

/**
 * 开启WebSocket支持
 */
@Configuration  
public class WebSocketConfig {  
    
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();  
    }  
  
}
  1. 创建WebSocket服务端

①通过注解@ServerEndpoint来声明实例化WebSocket服务端。(注意配置@Component才能被spring扫描)

② 通过注解@OnOpen、@OnMessage、@OnClose、@OnError 来声明回调函数。

 

 

 

③发送消息:new Session().getBasicRemote().sendText(message);

 

  • WebSocket服务类编写

    这里对照下面的代码看:

      1. 第20行,@ServerEndpoint("/websocket/{userID}"),括号中的内容就是客户端请求Socket连接时的访问路径,userID是我要求客户端传来的参数,我这里算是为了标识该客户端吧。
      2. 第28行,在该类中添加属性 userID,并添加对应的getUserID()方法。
      3. 第46行,在onOpen()方法即建立连接的时候就接收参数userID,需要标识@PathParam("userID") 。接收参数后直接赋值给属性userID。
      4. 第140-157行,是针对特定客户端发送消息。服务器和客户端在建立连接成功后就生成了一个WebSocket对象,并存在集合中,对象里特有的属性是我们设置的userID。所以通过唯一的userID就能标识服务器与该客户端建立的那个连接啦!这样要求发送消息时,传入userID与消息,服务器在自己的WebSocket连接集合中遍历找到对应客户端的连接,就可以直接发消息过去啦~~
package com.cuc.happyseat.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/*@ServerEndpoint注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/websocket/{userID}")
@Component
public class WebSocketServer {
    
        //每个客户端都会有相应的session,服务端可以发送相关消息
        private Session session;

        //接收userID
        private Integer userID;
        
        //J.U.C包下线程安全的类,主要用来存放每个客户端对应的webSocket连接
        private static CopyOnWriteArraySet<WebSocketServer> copyOnWriteArraySet = new CopyOnWriteArraySet<WebSocketServer>();

        public Integer getUserID() {
            return userID;
        }
         
       /**
       * @Name:onOpen
       * @Description:打开连接。进入页面后会自动发请求到此进行连接
       * @Author:mYunYu
       * @Create Date:14:46 2018/11/15
       * @Parameters:@PathParam("userID") Integer userID
       * @Return:
       */
        @OnOpen
        public void onOpen(Session session, @PathParam("userID") Integer userID) {
            this.session = session;
            this.userID = userID;
            System.out.println(this.session.getId());
            //System.out.println("userID:" + userID);
            copyOnWriteArraySet.add(this);
            System.out.println("websocket有新的连接, 总数:"+ copyOnWriteArraySet.size());

        }

       /**
       * @Name:onClose
       * @Description:用户关闭页面,即关闭连接
       * @Author:mYunYu
       * @Create Date:14:46 2018/11/15
       * @Parameters:
       * @Return:
       */
        @OnClose
        public void onClose() {
            copyOnWriteArraySet.remove(this);
            System.out.println("websocket连接断开, 总数:"+ copyOnWriteArraySet.size());
        }

        /**
        * @Name:onMessage
        * @Description:测试客户端发送消息,测试是否联通
        * @Author:mYunYu
        * @Create Date:14:46 2018/11/15
        * @Parameters:
        * @Return:
        */
        @OnMessage
        public void onMessage(String message) {
            System.out.println("websocket收到客户端发来的消息:"+message);
        }

        /**
        * @Name:onError
        * @Description:出现错误
        * @Author:mYunYu
        * @Create Date:14:46 2018/11/15
        * @Parameters:
        * @Return:
        */
        @OnError
        public void onError(Session session, Throwable error) {
            System.out.println("发生错误:" + error.getMessage() + "; sessionId:" + session.getId());
            error.printStackTrace();
        }

        public void sendMessage(Object object){
            //遍历客户端
            for (WebSocketServer webSocket : copyOnWriteArraySet) {
                System.out.println("websocket广播消息:" + object.toString());
                try {
                    //服务器主动推送
                    webSocket.session.getBasicRemote().sendObject(object) ;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
        * @Name:sendMessage
        * @Description:用于发送给客户端消息(群发)
        * @Author:mYunYu
        * @Create Date:14:46 2018/11/15
        * @Parameters:
        * @Return:
        */
        public void sendMessage(String message) {
            //遍历客户端
            for (WebSocketServer webSocket : copyOnWriteArraySet) {
                System.out.println("websocket广播消息:" + message);
                try {
                    //服务器主动推送
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
        * @throws Exception 
         * @Name:sendMessage
        * @Description:用于发送给指定客户端消息
        * @Author:mYunYu
        * @Create Date:14:47 2018/11/15
        * @Parameters:
        * @Return:
        */
        public void sendMessage(Integer userID, String message) throws Exception {
            Session session = null;
            WebSocketServer tempWebSocket = null;
            for (WebSocketServer webSocket : copyOnWriteArraySet) {
                if (webSocket.getUserID() == userID) {
                    tempWebSocket = webSocket;
                    session = webSocket.session;
                    break;
                }
            }
            if (session != null) {
                //服务器主动推送
                tempWebSocket.session.getBasicRemote().sendText(message);
                
            } else {
                System.out.println("没有找到你指定ID的会话:{}"+ "; userId:" + userID);
            }
        }


    
}
  • Controller类的编写。
    1. 我在看博客的时候,发现有的博主写了Controller类,有的没写,我就有点疑惑了。后来,咳咳,发现特地写了一个Controller类只是为了测试。。
    2. 一般在实际项目中,在确保建立连接过程没有问题的情况下,我们就直接在一些写好的接口中写 WebSocketServer.sendMessage(param, message)语句就行了。
    3. 也因此,你写的位置就决定了你什么时候给你的客户端发消息,这样也就实现了主动推送消息的功能咯~

前提是:在你的Controller类里,以@Resource的方式注入WebSocket,而不是@Autowired方式哦(⊙o⊙)。

 

@Resource
    WebSocketServer webSocket;
@Autowired
     UserService userService;

调用示例:

    if(userID>0) {
            boolean location = userService.getLocation(userID);
            if(location==false) {//验证用户当前不在馆内
                boolean i = userService.modifyLocation(userID, true);
                if(i==true) {
                modelMap.put("successEnter", true);
                
                //发消息给客户端
                webSocket.sendMessage(userID, "success");
                }
            }else {
                modelMap.put("successEnter", false);
                //发消息给客户端
                webSocket.sendMessage(userID, "fail");
            }
        }else {
            modelMap.put("successEnter", false);
            //发消息给客户端
            webSocket.sendMessage(userID, "fail");
        }

 

小程序是只支持https访问的,所以得用wss

 

 

 嘿嘿嘿,下面是学习WebSocket过程中参考的几篇博文:

 

转载:https://www.cnblogs.com/codecheng/archive/2019/04/06/10657530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot 框架支持使用 WebSocket 协议进行通信。可以使用 Spring Boot 的内置支持来配置 WebSocket,也可以使用第三方库如 Spring WebSocket 来实现 WebSocket 功能。使用 Spring Boot 可以简化 WebSocket 的配置和使用。 ### 回答2: SpringBoot是一个非常流行的Java web框架,而WebSocket则是一种全新的web通信协议,通过 WebSocket 可以实现 Web 页面与服务器的实时双向通信。SpringBootWebsocket模块提供了强大的支持,使得使用 WebSocket 开发项目变得更加容易。 在springboot使用websocket,首先需要引入Spring的WebSocket模块以及对应的STOMP协议的依赖,可以通过在pom.xml中添加以下依赖实现: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 在Spring Boot应用程序中使用WebSocket非常容易,我们可以分为以下几个步骤: 1. 创建一个WebSocket配置类 在WebSocket配置类中,需要添加@EnableWebSocketMessageBroker和@Configuration注解。其中,@EnableWebSocketMessageBroker注解表示开启WebSocket消息代理支持,@Configuration注解表示该类为配置类。 ``` @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { // TODO 添加相关配置 } ``` 2. 配置WebSocket消息代理 在WebSocketConfig中,需要重写configureMessageBroker方法,来配置WebSocket消息代理。在该方法中,需要首先调用enableSimpleBroker方法,它用于配置简单的消息代理,使得订阅者能够订阅消息。 ``` @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); } ``` 3. 配置WebSocket请求路径 在WebSocketConfig中,需要重写registerStompEndpoints方法,来配置WebSocket请求路径。该方法中,需要调用addEndpoint方法,来注册一个WebSocket端点(/chat),供客户端访问。 ``` @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").withSockJS(); } ``` 4. 编写WebSocket消息处理类 编写一个WebSocket消息处理类,用来处理WebSocket相关的消息和事件。需要在类上添加@Controller注解,同时在方法上添加@MessageMapping注解,用来指定方法处理的消息地址。 ``` @Controller public class ChatController { @MessageMapping("/msg") @SendTo("/topic/messages") public ChatMessage sendMessage(@Payload ChatMessage chatMessage) { return chatMessage; } } ``` 5. 编写WebSocket客户端代码 最后,我们需要编写WebSocket客户端代码来测试WebSocket通信。在客户端代码中,需要先建立与服务器的连接,然后通过WebSocket发送和接收消息。 ``` var socket = new SockJS('/chat'); var stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { stompClient.subscribe('/topic/messages', function (chatMessage) { console.log(chatMessage); }); }); function sendMessage() { var message = {sender: 'Alice', content: 'Hello!'}; stompClient.send("/app/msg", {}, JSON.stringify(message)); } ``` 以上就是使用SpringBoot开发WebSocket的主要步骤,通过这些步骤,我们可以轻松地开发出基于WebSocket的实时通讯功能。总体来说,SpringBootWebSocket模块提供了强大的支持,使得使用WebSocket开发项目变得更加容易。 ### 回答3: Springboot是一个开源的Java框架,用于创建可扩展的基于RESTful的Web应用程序。其中,Websocket是一种协议,使用在客户端和服务端之间进行实时通信。在Springboot使用Websocket可以用于实现即时通信、聊天、实时数据交换等功能。 Springboot使用Websocket需要两个方面:客户端代码和服务端代码。在客户端的代码中,需要引入一个websocket库,例如SockJS或Stomp;在服务端的代码中,则需要使用@ServerEndpoint注解,并为Websocket注册处理类。 Websocket使用的过程中,客户端会建立与服务端的一条持久连接,以进行数据交换。在客户端与服务端建立连接之后,可以发送消息到服务端并通过该连接接收来自服务端的消息。 SpringbootWebsocket还支持多个连接的概念,即多个客户端可以与服务端建立多个连接,之间不会相互干扰。 在Springboot使用Websocket的优点是它提供了一个简便易用的方式来实现低延迟的双向通信,同时又减少了对HTTP请求的频繁使用,从而提升Web应用的性能和效率。 总之,Springboot使用Websocket是一种方便实用的方式,可以省略掉复杂的代码和步骤,同时还可以快速开发多种实时通信功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值