springboot WebSocket 实现聊天功能(代码纯享)

本文介绍了一个使用SpringBoot实现的WebSocket应用案例,包括了pom依赖配置、WebSocket类的实现、配置类、枚举类、控制器及启动类的代码细节。通过用户与客服间的互动演示了如何进行实时消息传递。

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

pom引用

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
WebSocket 类
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.thymeleaf.util.MapUtils;

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

/**
 * @Auther: shigc
 * @Date: 2018/12/15 11:53
 * @Description: websocket
 */
@Slf4j
@ServerEndpoint("/websocket/{sid}/{type}")
@Component
public class WebSocket {

    /**
     * 静态变量,用来记录当前在线连接数。线程安全。
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     */

    //用户与客服绑定
    public static Map<String, String> electricSocketCust = new ConcurrentHashMap<>();
    //缓存用户信息
    public static Map<String, Session> userMap = new ConcurrentHashMap<>();
    //空闲客服
    public static Map<String, Session> idlekfMap = new ConcurrentHashMap<>();
    //所有信息
    public static Map<String, Session> allMap = new ConcurrentHashMap<>();

    public static Map<String, Session> haveRead = new ConcurrentHashMap<>();
    public static Boolean haveReadf = false;

    /**
     * 接收sid
     */
    private String sid = "";
    private String type = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid, @PathParam("type") String type) throws IOException {
        this.sid = sid;
        this.type = type;
        //缓存信息
        this.identity(type, sid, session);
        // 在线数加1
        addOnlineCount();
        log.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
        //匹配客服并发送信息
        match(type, sid);
        //匹配全员通知
        if (haveReadf && !haveRead.containsKey(sid)) {
            Session session23 = allMap.get(sid);
            if (session23 != null) {
                session23.getBasicRemote().sendText("全员通知");
            }
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //绑定删除
        String str = electricSocketCust.get(sid);
        if (!StringUtils.isEmpty(str)) {
            electricSocketCust.remove(str);
        }
        //是否是用户关闭链接
        if (userMap.containsKey(sid) && !StringUtils.isEmpty(str)) {
            //客服加入空闲
            idlekfMap.put(str, allMap.get(str));
        }

        allMap.remove(sid);
        idlekfMap.remove(sid);
        userMap.remove(sid);
        electricSocketCust.remove(sid);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("收到来自窗口" + sid + "的信息:" + message);
        //消息
        String ssid = electricSocketCust.get(sid);
        if (StringUtils.isEmpty(ssid)) {
            match(type, sid);
        }
        ssid = electricSocketCust.get(sid);
        if (StringUtils.isEmpty(ssid)) {
            session.getBasicRemote().sendText(message);
        } else {
            Session sessionss = allMap.get(ssid);
            sessionss.getBasicRemote().sendText(message);
            session.getBasicRemote().sendText(message);
        }
    }

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


    /**
     * 给指定用户发消息
     * message 消息
     * sid 发送着sid
     */
    public void sendInfo(String message, String sid) throws IOException {
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);
        Session session = allMap.get(sid);
        if (session != null) {
            session.getBasicRemote().sendText(message);
        }
        String s = electricSocketCust.get(sid);
        if (!StringUtils.isEmpty(s)) {
            Session session1 = allMap.get(s);
            session1.getBasicRemote().sendText(message);
        }

    }

    /**
     * 后台给指定发消息(忠告)
     * message 消息
     * sid 发送着sid
     */
    public void closeAll() {
        //为空就是全员

    }


    /**
     * 后台给指定发消息(忠告)
     * message 消息
     * sid 发送着sid
     */
    public void sendInfoAdmin(String message, String sid) throws IOException {
        //为空就是全员
        log.info("推送消息到窗口" + sid + ",推送内容:" + message);
        if ("0".equals(sid)) {
            if (!MapUtils.isEmpty(userMap)) {
                for (String sids : userMap.keySet()) {
                    Session session = userMap.get(sids);
                    session.getBasicRemote().sendText(message);
                    haveRead.put(sids, session);
                    haveReadf = true;
                }
            }
        } else {
            Session session = allMap.get(sid);
            if (session != null) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        WebSocket.onlineCount.addAndGet(1);
    }

    public static void subOnlineCount() {
        WebSocket.onlineCount.decrementAndGet();
    }


    /**
     * 保存链接信息
     *
     * @param identity, sid, session
     * @author X-MD
     * @date 2020/9/10 0010
     **/
    private void identity(String identity, String sid, Session session) {
        allMap.put(sid, session);
        if ("cust".equals(identity)) {
            idlekfMap.put(sid, session);
        }
        if ("user".equals(identity)) {
            userMap.put(sid, session);
        }
    }

    private void match(String identity, String sid) throws IOException {
        if ("user".equals(identity)) {
            //有客服在线
            if (!MapUtils.isEmpty(idlekfMap)) {
                //客服sid
                String custSid = null;
                for (String keys : idlekfMap.keySet()) {
                    custSid = keys;
                }
                //绑定关系
                electricSocketCust.put(sid, custSid);
                electricSocketCust.put(custSid, sid);
                idlekfMap.remove(custSid);
                //发送消息
                String ssad = "你好,我是" + Bcabn.findByKey(custSid) + "很高兴为你服务";
                sendInfo(ssad, sid);
            }
        }
    }
}
WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author X-MD
 * @Date 2020/9/9 0009
 * @description:
 **/

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter (){
        return new ServerEndpointExporter();
    }
}
Bcabn 枚举类
public enum Bcabn {
    ONE("1", "马云"),
    TWO("2", "马化腾"),
    THEW("3", "刘强东"),
    FOUR("4", "李彦宏");

    /**
     * 队列名称
     */
    public String key;
    /**
     * 路由键
     */
    public String value;

    Bcabn(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public static String findByKey(String key) {
        String s = null;
        for (Bcabn bcabn : values()) {
            if (bcabn.getKey().equals(key)) {
                s = bcabn.getValue();
            }
        }
        return s;
    }

    private String getKey() {
        return this.key;
    }

    private String getValue() {
        return this.value;
    }
}
WebSocketController
@RestController
@RequestMapping("/webSocket")
public class WebSocketController {

    @Autowired
    WebSocket webSocket;

    @GetMapping("/server/push/{sid}")
    public void push(@PathVariable("sid") Integer sid) throws IOException {
        webSocket.sendInfoAdmin("注意啦! -> ", String.valueOf(sid));
    }

    @GetMapping("/server/closeall")
    public void closeAll() {
        webSocket.closeAll();
    }
}

启动类

@SpringBootApplication
@EnableWebSocket
public class WebsocketserviceApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebsocketserviceApplication.class, args);
    }

}

 html1 (用户)

<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>springboot项目WebSocket测试demo</title>
</head>
<body>
<h3>springboot项目websocket测试demo</h3>
<h4>测试说明</h4>
<h5>文本框中数据数据,点击‘发送测试’,文本框中的数据会发送到后台websocket,后台接受到之后,会再推送数据到前端,展示在下方;点击关闭连接,可以关闭该websocket;可以跟踪代码,了解具体的流程;代码上有详细注解</h5>
<br/>
<input id="text" type="text"/>
<button onclick="send()">发送测试</button>
<hr/>
<button onclick="clos()">关闭连接</button>
<hr/>
<div id="message"></div>
<script>
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://127.0.0.1:8888/websocket/1/user");
    } else {
        alert("您的浏览器不支持websocket");
    }
    websocket.onerror = function () {
        setMessageInHtml("send error!");
    }
    websocket.onopen = function () {
        setMessageInHtml("connection success!")
    }
    websocket.onmessage = function (event) {
        setMessageInHtml(event.data);
    }
    websocket.onclose = function () {
        setMessageInHtml("closed websocket!")
    }
    window.onbeforeunload = function () {
        clos();
    }

    function setMessageInHtml(message) {
        document.getElementById('message').innerHTML += message+"</br>";
    }

    function clos() {
        websocket.close(3000, "强制关闭");
    }

    function send() {
        var msg2 = document.getElementById('text').value;
        websocket.send(msg2);
    }
</script>
</body>
</html>

html2(客服)

<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>springboot项目WebSocket测试demo</title>
</head>
<body>
<h3>springboot项目websocket测试demo</h3>
<h4>测试说明</h4>
<h5>文本框中数据数据,点击‘发送测试’,文本框中的数据会发送到后台websocket,后台接受到之后,会再推送数据到前端,展示在下方;点击关闭连接,可以关闭该websocket;可以跟踪代码,了解具体的流程;代码上有详细注解</h5>
<br/>
<input id="text" type="text"/>
<button onclick="send()">发送测试</button>
<hr/>
<button onclick="clos()">关闭连接</button>
<hr/>
<div id="message"></div>
<script>
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://127.0.0.1:8888/websocket/2/cust");
    } else {
        alert("您的浏览器不支持websocket");
    }
    websocket.onerror = function () {
        setMessageInHtml("send error!");
    }
    websocket.onopen = function () {
        setMessageInHtml("connection success!")
    }
    websocket.onmessage = function (event) {
        setMessageInHtml(event.data);
    }
    websocket.onclose = function () {
        setMessageInHtml("closed websocket!")
    }
    window.onbeforeunload = function () {
        clos();
    }

    function setMessageInHtml(message) {
        document.getElementById('message').innerHTML += message + "</br>";
    }

    function clos() {
        websocket.close(3000, "强制关闭");
    }

    function send() {
        var msg2 = document.getElementById('text').value;
        websocket.send(msg2);
    }
</script>
</body>
</html>

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢了尾巴的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值