SpringBoot集成WebSocket

pom添加配置

bash 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

代码目录结构

WebsocketConfiguration

bash 复制代码
package com.ruoyi.framework.socket.config;

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

@Configuration
public class WebsocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        System.out.println("(♥◠‿◠)ノ゙   WebSocket服务开启   ლ(´ڡ`ლ)゙");
        return new ServerEndpointExporter();
    }
}
bash 复制代码
package com.ruoyi.framework.socket.ctrl;

import com.ruoyi.framework.socket.service.WebSocketService;

public class Distribute {

   public static void send(WebSocketService webSocketService){
       webSocketService.pushMsg();
   }
}
bash 复制代码
package com.ruoyi.framework.socket.ctrl;

import com.ruoyi.framework.socket.pojo.Message;
import com.ruoyi.framework.socket.service.WebSocketService;

/**
 * 全部推送
 */
public class MultipleSending extends WebSocketService {


    public MultipleSending(String msg){
        Message message=new Message();
        message.setPushClient("ALL");
        message.setMessage(msg);
        this.message=message;
    }

    @Override
    public void send() {
        this.sendAll(this.message.getMessage());
    }
}
bash 复制代码
package com.ruoyi.framework.socket.ctrl;


import com.ruoyi.framework.socket.pojo.Message;
import com.ruoyi.framework.socket.service.WebSocketService;

/**
 * 单个发送
 */
public class SingleSending extends WebSocketService {

    public SingleSending(Message message){
        this.message=message;
    }

    @Override
    public void send() {
        this.sendToUser(this.message.getMessage(),this.message.getPushClient());
    }
}
bash 复制代码
package com.ruoyi.framework.socket.pojo;

import com.alibaba.fastjson.JSONObject;

public class Message {

    private String messageType;

    private String message;

    private String pushClient;


    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setMessage(JSONObject message) {
        this.message = message.toString();
    }

    public String getPushClient() {
        return pushClient;
    }

    public void setPushClient(String pushClient) {
        this.pushClient = pushClient;
    }

    public String toJson(){
        return JSONObject.toJSONString(this);
    }
}
bash 复制代码
package com.ruoyi.framework.socket.service;


import com.ruoyi.framework.socket.pojo.Message;
import com.ruoyi.framework.socket.socketBase.WebSocketServer;
import com.ruoyi.framework.socket.utils.SocketException;

public abstract class WebSocketService extends WebSocketServer {

    protected Message message;

    //推送消息
    public boolean pushMsg(){
        try {
            System.out.println("--------------------- check Data ----------------");
            check();
            System.out.println("--------------------- check Data end----------------");
            System.out.println("--------------------- push Message----------------");
            this.send();
            System.out.println("--------------------- push Message end----------------");
            return true;
        }catch (SocketException socketException){
            return false;
        }catch (Throwable throwable){
            return false;
        }
    }

    private void check() throws SocketException {
        this.checkItem(this.message.getMessageType());
        this.checkItem(this.message.getMessage());
        this.checkItem(this.message.getPushClient());
    }

    private void checkItem(String str) throws SocketException {
        if (str==null||str.trim().isEmpty()){
            throw new SocketException("关键数据不能为空");
        }
    }

    public abstract void send();
}
bash 复制代码
package com.ruoyi.framework.socket.socketBase;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.socket.ctrl.SingleSending;
import com.ruoyi.framework.socket.pojo.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * socket端口
 */
@ServerEndpoint("/socket/{clientId}")
@Component
public class WebSocketServer {
    
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 会话
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private static Map<Object, Object> clientsBak = new ConcurrentHashMap<>();

    //接入
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        log.info("【接入SOCKET】=====clientId====="+clientId+"======接入时间======"+ DateUtils.getTime());
        //将新用户存入在线的组
        clientsBak.put(session.getId(),clientId);
        clients.put(clientId, session);
    }

    /**
     * 离线
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("【断开SOCKET】====="+session.getId()+"======date======"+DateUtils.getTime());
        clients.remove(clientsBak.get(session.getId()));
        clientsBak.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message,Session session) {

        log.info("发送者:"+session.getId()+"报文--->"+message);
    }

    /**
     * 消息广播
     * @param message 消息内容
     */
    public final void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }
    //推送
    public final void sendToUser(String msg,String id){
        clients.get(id).getAsyncRemote().sendText(msg);
    }


    //在线人数
    public final static int onLineSize(){
        return clients.size();
    }

    /*
        查看某个id是否在线
     */
    public final static boolean onLine(String key){
        return clients.containsKey(key);
    }
}

package com.ruoyi.framework.socket.utils;

public class SocketException extends Exception{

复制代码
public SocketException(){
    super();
}

public SocketException(String message){
    super(message);
}

public SocketException(String message, Throwable cause){
    super(message,cause);
}

public SocketException(Throwable cause) {
    super(cause);
}

}

测试 客户端链接服务端发送消息

服务端给客户端发送消息

相关推荐
qq_12498707533 小时前
基于springboot归家租房小程序的设计与实现(源码+论文+部署+安装)
java·大数据·spring boot·后端·小程序·毕业设计·计算机毕业设计
内存不泄露3 小时前
基于Spring Boot和Vue的宠物医院管理系统设计与实现
vue.js·spring boot·信息可视化
廋到被风吹走4 小时前
【Spring】Spring Boot Actuator 深度解析:健康检查、指标暴露与端点安全
spring boot·安全·spring
怦怦蓝4 小时前
详解 IntelliJ IDEA 中编写邮件发送功能(从环境搭建到实战落地)
java·spring boot·intellij-idea
克里斯蒂亚诺更新4 小时前
理解即时通信Socket以及用NodeJs实现WebSocket
网络·websocket·网络协议
码农很忙4 小时前
从0到1搭建实时日志监控系统:基于WebSocket + Elasticsearch的实战方案
websocket·网络协议·elasticsearch
幽络源小助理4 小时前
springboot基于Java的教学辅助平台源码 – SpringBoot+Vue项目免费下载 | 幽络源
java·vue.js·spring boot
杜子不疼.6 小时前
计算机视觉热门模型手册:Spring Boot 3.2 自动装配新机制:@AutoConfiguration 使用指南
人工智能·spring boot·计算机视觉
indexsunny7 小时前
互联网大厂Java求职面试实战:Spring Boot微服务与Redis缓存场景解析
java·spring boot·redis·缓存·微服务·消息队列·电商
28岁青春痘老男孩13 小时前
JDK8+SpringBoot2.x 升级 JDK 17 + Spring Boot 3.x
java·spring boot