spring boot 注解方式实现websocket

本文介绍如何使用Spring Boot实现WebSocket功能,包括pom文件引入依赖、添加@EnableWebSocket注解、配置WebSocket并创建WebSocket服务器实现类。同时提供前端测试代码。

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

1,pom文件引入websocket包:

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

2,启动类添加@EnableWebSocket注解,启动支持websocket

3,创建websocket配置类



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


@Configuration
public class WebSocketConfig {

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

4,创建WebSocket实现@ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}")注解中的路径是前端发送请求的路径,同时 从路径里面获取前端参数



import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}")
@Component
@Slf4j
public class WebSocketServer {
    private static int onlineCount=0;
    private static ConcurrentHashMap<String,ConcurrentHashMap<String,WebSocketServer>> webSocketMap=new ConcurrentHashMap<String,ConcurrentHashMap<String, WebSocketServer>>();
    private Session session;
    private String novelId="";
    private String userSessionId="";
    @OnOpen
    public void onOpen(Session session, @PathParam("novelId") String novelId ,@PathParam("userSessionId") String userSessionId,EndpointConfig config){
        this.session=session;
        this.novelId=novelId;
        this.userSessionId=userSessionId;
        ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId);
        if (novelMap ==null){
            ConcurrentHashMap<String, WebSocketServer>  noticeMap= new ConcurrentHashMap<>();
            noticeMap.put(userSessionId,this);
            webSocketMap.put(novelId,noticeMap);
        }else{
            WebSocketServer webSocketServer = novelMap.get(userSessionId);
            if (webSocketServer==null){
                novelMap.put(userSessionId,this);
                webSocketMap.put(novelId,novelMap);
            }
        }
        addOnlineCount();
        log.info("webSocket连接成功------》当前在线人数:"+getOnlineCount());
    }
    public static void sendInfo(String message,@PathParam("novelId") String novelId,@PathParam("userSessionId") String userSessionId) {
        Iterator<Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>>> iterator = webSocketMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>> next = iterator.next();
            if (next.getKey().equals(novelId)){
                ConcurrentHashMap<String, WebSocketServer> value = next.getValue();
                Enumeration<String> keys = value.keys();
                while (keys.hasMoreElements()){
                    String s = keys.nextElement();
                    value.get(s).sendMessage(message);
                }
            }
        }
    }

    public void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("WebSocket推送消息异常:{}",e);
        }
    }

    @OnClose
    public void onClose() {
        ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId);
        if (novelMap ==null){
            webSocketMap.remove(novelId);
        }else{
            novelMap.remove(userSessionId);
            webSocketMap.put(novelId,novelMap);
        }
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

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

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

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

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

附上前端测试代码

<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <title>websocket测试</title>
    <script src="http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>
      <script type="text/javascript">
         function WebSocketTest()
         {
          var ws=null;
            if ("WebSocket" in window)
            {
               console.log("您的浏览器支持 WebSocket!"); 
               // 打开一个 web socket
              ws = new WebSocket("ws://127.0.0.1:8080/websocket/test/test");
            }
            else
            {
              console.log("浏览器不支持 WebSocket!");
               // 浏览器不支持 WebSocket

            }

                ws.onopen = function()
               {
                  console.log("WebSocket------>已打开");
               };
             
               ws.onmessage = function (msg) 
               { 
                  console.log(msg.data);
                  console.log("WebSocket------->发现消息");
               };
                
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  console.log("连接已关闭..."); 
               };
         }
      </script>
        
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
  
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值