SpringBoot整合WebSocket

本文详细介绍了如何在SpringBoot项目中集成WebSocket,从搭建项目、导入依赖、配置类的编写到服务类的实现,最后通过创建HTML页面进行测试并展示了测试结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot整合WebSocket

1.搭建一个的SpringBoot项目

在这里插入图片描述

2.导入WebSocket依赖

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

3.添加配置类

具体代码如下

package com.example.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
 * @date 2019/9/25 15:29
 * @author ww
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

4.添加一个配置WebSocket的服务类

具体代码如下

package com.example.websocket.ws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
/**
 * websocket服务类
 * @date 2019/9/25 15:30
 * @author ww
 */
@ServerEndpoint(value = "/webSocket")
@Component
public class WebSocketServer {
    /**
     * 在线数  静态变量,用来记录当前在线连接数,应该把它设计出线程安全的
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的websocket对象
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 日志
     */
    private final Logger log = LoggerFactory.getLogger(getClass());
    /**
     * 连接建立成功后调用的方法
     * @param session 可选的参数,session为与某个客户端的连接会话
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.info("有新的连接加入!当前连接数为:{}",getOnlineCount());
        try {
            sendMessage("连接成功");
        }catch (IOException e) {
            log.error("websocket异常" + e.getMessage());
        }
    }
    /**
     * 关闭连接时调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一个连接关闭!当前连接数为:{}",getOnlineCount());
    }
    /**
     * 消息发送
     * @param msg 消息
     * @throws IOException 发送出现异常
     */
    public void sendMessage(String msg) throws IOException {
        session.getBasicRemote().sendText(msg);
    }
    /**
     * 发送错误
     * @param error 错误信息
     */
    @OnError
    public void onError(Throwable error) {
        log.info("发生错误:{}",error.getMessage());
    }
    /**
     * 收到客户端的消息后调用的方法
     * @param message 客户端发来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("来自客户端的消息:{}",message);
        //消息群发
        webSocketSet.forEach( item -> {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * 获取在线数
     * @return 返回在线数
     */
    private static synchronized  int getOnlineCount() {
        return onlineCount;
    }
    /**
     * 新增在线数
     */
    private static synchronized void addOnlineCount() {
        onlineCount ++;
    }
    /**
     * 减少在线数
     */
    private static synchronized void subOnlineCount() {
        onlineCount--;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) { return true;}
        if (o == null || getClass() != o.getClass()) { return false;}
        WebSocketServer that = (WebSocketServer) o;
        return Objects.equals(session, that.session);
    }
    @Override
    public int hashCode() {
        return Objects.hash(session);
    }
}

5.测试

创建一个html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>WebSocket Echo Demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
  <script>
  var ws = new WebSocket("ws://localhost:8081/webSocket");
  ws.onopen = function (e) {
    console.log('Connection to server opened');
  }
  function sendMessage() {
    ws.send($('#message').val());
  }
    ws.onmessage = function (evt) { 
	  var received_msg = evt.data;
	  alert(received_msg);
   };
   ws.onclose = function(){ 
	  // 关闭 websocket
	  alert("连接已关闭..."); 
   };
	ws.onerror = function(err) { 
		alert("Error: " + err);    
	};
  </script>
</head>

<body >
  <div class="vertical-center">
    <div class="container">
      <p> </p>
      <form role="form" id="chat_form" onsubmit="sendMessage(); return false;">
        <div class="form-group">
          <input class="form-control" type="text" name="message" id="message"
              placeholder="Type text to echo in here" value="" />
        </div>
        <button type="button" id="send" class="btn btn-primary"
            onclick="sendMessage();">
          	Send!
        </button>
      </form>
    </div>
  </div>
</body>
</html>

测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值