springboot集成WebSocket向指定用户发送消息(亲测可用!)

依赖

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

配置类

package com.yupont.xc.config;

import org.apache.catalina.session.StandardSessionFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {
     private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
    @Override
    /**
     * 修改握手信息
     */
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        StandardSessionFacade ssf = (StandardSessionFacade) request.getHttpSession();
        if (ssf != null) {
                   HttpSession httpSession = (HttpSession) request.getHttpSession();
                  //关键操作
                  sec.getUserProperties().put("sessionId", httpSession.getId());
            log.info("获取到的SessionID:" + httpSession.getId());
                 }
        super.modifyHandshake(sec, request, response);

    }
    @Bean
   public ServerEndpointExporter serverEndpointExporter() {
             //这个对象说一下,貌似只有服务器是tomcat的时候才需要配置,具体我没有研究
            return new ServerEndpointExporter();
          }
}

核心类

package com.yupont.xc.task;

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

import javax.websocket.*;

import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import com.yupont.xc.config.WebSocketConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@ServerEndpoint(value = "/websocket/{id}", configurator = WebSocketConfig.class)
@Component
public class WebSocketServer {

    static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //指定的sid,具有唯一性,暫定為用戶id
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session, EndpointConfig config) {
        //获取WebsocketConfig.java中配置的“sessionId”信息值
        String httpSessionId = (String) config.getUserProperties().get("sessionId");
        this.session = session;
        this.sid=id;


        webSocketSet.put(sid,this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("用戶"+sid+"加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("Hello world");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
    }

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

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     *
     */
    public  boolean sendtoUser(String message,String sendUserId) throws IOException {
       if(sendUserId==null){
           for (String key : webSocketSet.keySet()) {
               try {
                   webSocketSet.get(key).sendMessage(message);

               } catch (IOException e) {
                   e.printStackTrace();

               }
           }


       }else {
           if (webSocketSet.get(sendUserId) != null) {
               if(!sid.equals(sendUserId)){
                   log.info("未找到匹配用戶");
                   return false;
               }{
                   webSocketSet.get(sendUserId).sendMessage(message);
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   log.info("消息發送成功");
                   return true;
               }
           } else {
               //如果用户不在线则返回不在线信息给自己
               log.info("未找到匹配用戶");
               return false;
           }
       }
        return true;
    }


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

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

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

调用时html写法
注意到评论区的一些问题,统一解答:请求连接中的12是具有唯一性的客户端ID,你可以定义为用户ID,也可以是UUID,不能重复,否则服务器无法定位到客户端,或者多台客户端在服务器却只显示一台

   <!DOCTYPE html>
<html>

<head>
<title>Title of the document</title>
<script src="jquery-1.8.3.js"></script>
</head>

<body>
The content of the document......
</body>
 <script> 
    var socket;  
    if(typeof(WebSocket) == "undefined") {  
        console.log("您的浏览器不支持WebSocket");  
    }else{  
        console.log("您的浏览器支持WebSocket");  
        	//实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接  
            //等同于socket = new WebSocket("ws://localhost:8087//websocket");  
            socket = new WebSocket("ws://localhost:8087/websocket/12");  
            //打开事件  
            socket.onopen = function() {  
                console.log("Socket 已打开");  
                socket.send("这是来自客户端的消息");  
            };  
            //获得消息事件  
            socket.onmessage = function(msg) {  
                console.log(msg.data);  
                //发现消息进入    开始处理前端触发逻辑
            };  
            //关闭事件  
            socket.onclose = function() {  
                console.log("Socket已关闭");  
            };  
            //发生了错误事件  
            socket.onerror = function() {  
                alert("Socket发生了错误");  
                //此时可以尝试刷新页面
            }  
            //离开页面时,关闭socket
            //jquery1.8中已经被废弃,3.0中已经移除
            // $(window).unload(function(){  
            //     socket.close();  
            //});  
    }
    </script> 
</html>

  
不要导错参数包哟



猜你喜欢

转载自blog.csdn.net/qq_41700030/article/details/100777937