SpringBoot 结合 WebSocket 实现双向通信

一、WebSocket简介

        HTTP协议只能单方面从浏览器/客户端往服务器发送请求,服务器不能主动向浏览器/客户端推送消息,WebSocket使得浏览器/客户端具备了实时双向通信的能力。

二、SpringBoot整合WebSocket

        作为后端开发主流框架SpringBoot,整合WebSocket相对简单很多。

1、pom引入WebSocket依赖

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

2、配置WebSocket

        这一步主要是配置WebSocket,通过@Configuration注解将ServerEndpointExporter类交由Spring容器管理,这个Bean在初始化时会扫描项目中@ServerEndpoint注解的类,这个类就是WebSocket通信的主要类。所以必须配置WebSocket才能开启WebSocket功能。

// 开启Socket支持 扫描@ServerEndpoint
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
        return new ServerEndpointExporter();
    }
}

3、WebSocket通信处理类

/*
 * @ ServerEndpoint
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */

@Slf4j
@Service
@ServerEndpoint("/api/webSocket/{sid}")
public class WebSocketServer {
    //静态变量,用来记录当前在线连接数。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private String sid = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        this.session = session;
        webSocketSet.add(this);
        this.sid = sid;
        addOnlineCount();
        try {
            sendMessage("conn_success");
            log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.debug("remove this: {}", this);
        subOnlineCount();
        //断开连接,更新占用情况
        log.info("释放的sid为:"+sid);
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session){
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error){
        log.error("{}发生错误",session);
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    // 没啥用,重复的
    public static void sendInfo(String message, @PathParam("sid") String sid){
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);
        for(WebSocketServer item : webSocketSet){
            try{
                if(message.isEmpty()){
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static CopyOnWriteArraySet getWebSocketSet() {
        return webSocketSet;
    }
}

        对应的注解及方法顾名思义可以知道对应的方法的作用。

4. 前段index.html

        这个可以整合进SpringBoot里测试,也可以通过Ningx反向代理,不过需要配置反向代理及Socket配置。

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
 let socket;
 function openSocket() {

  const socketUrl = "ws://自己的ip地址及端口/api/webSocket/" + $("#userId").val();
  console.log(socketUrl);
  if(socket!=null){
   socket.close();
   socket=null;
  }
  socket = new WebSocket(socketUrl);
  //打开事件
  socket.onopen = function() {
   console.log("websocket已打开");
  };
  //获得消息事件
  socket.onmessage = function(msg) {
   console.log(msg.data);
   //发现消息进入,开始处理前端触发逻辑
  };
  //关闭事件
  socket.onclose = function() {
   console.log("websocket已关闭");
  };
  //发生了错误事件
  socket.onerror = function() {
   console.log("websocket发生了错误");
  }
 }

 //将消息显示在网页上
 function setMessageInnerHTML(innerHTML) {
  document.getElementById('message').innerHTML += innerHTML + '<br/>';
 }
 //关闭WebSocket连接
 function closeWebSocket() {
  socket.close();
 }

 //发送消息
 function send() {
  var message = document.getElementById('text').value;
  socket.send('{"msg":"' + message + '"}');
  setMessageInnerHTML(message + "&#13;");
 }
</script>
<body>
<p>【socket开启者的ID信息】:<div><input id="userId" name="userId" type="text" value="10"></div>

Welcome<br/><input id="text" type="text" />
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="openSocket()">打开socket</button>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值