栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 整合WebSocket实现消息推送

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 整合WebSocket实现消息推送

1、pom.xml引入jar



    org.springframework.boot
    spring-boot-starter-websocket

2、创建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();
    }


}

3、创建WebSocket服务

import lombok.extern.slf4j.Slf4j;
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.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/socketServer/{uid}")
@Slf4j
public class WebSocketServer {

    private static UserService userService;
    // @Autowired只能在set方法注入,不然会null报错
    @Autowired
    public void setUserService(UserService userService) {
        WebSocketServer.userService = userService;
    }

    
    private static int onlineCount = 0;

    
    private Session session;

    
    private String uid = "";

    
    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();


    
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {
        log.info("用户连接建立成功:"+uid);
        this.session = session;
        this.uid = uid;
        if (webSocketMap.containsKey(uid)) {
            webSocketMap.remove(uid);
            //加入到set中
            webSocketMap.put(uid, this);
        } else {
            //加入set中
            webSocketMap.put(uid, this);
            //加入set中
            addOnlineCount();
            //在线数加1


        }
        try {

            sendMsg("{"status": "加入成功"}");
        } catch (IOException e) {
            log.error("用户:" + uid + ",网络异常!!!!!!");
        }
    }

    
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(uid)) {
            webSocketMap.remove(uid);
            //从set中删除
            subOnlineCount();
        }
    }

    
    @OnMessage
    public void onMessage(String message) {
        log.info("收到用户消息:"+uid+",报文:"+message);
        try {
            // 给uid发送消息
            webSocketMap.get(uid).sendMsg(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.uid + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    
    private void sendMsg(String msg) throws IOException {
        this.session.getBasicRemote().sendText(msg);
    }


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

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


}

4、可以自己创建一个测试页面链接websocket地址:

ws://localhost:8080/socketServer/40



    
    websocket测试

    





    点击测试连接 WebSocket




 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/845962.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号