java WebSocket带参数处理使用

1、webSocket实现代码

复制代码
@Component
public class WebSocketStompConfig {
    //这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket
    // ,如果你使用外置的tomcat就不需要该配置文件
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

@Component
@ServerEndpoint(value = "/webSocket")
@Slf4j
public class WebSocket {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, Set<Session>> webSocketMap  = new ConcurrentHashMap<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {

        this.session = session;
        // 获取URL中的参数
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> funcTypes = params.get("funcType");

        if (!funcTypes.isEmpty()) {
            // 取出funcType参数的值
            String funcType = funcTypes.get(0);

            if(webSocketMap.containsKey(funcType)){
                webSocketMap.get(funcType).add(session);
            }else{
                Set<Session> sessionSet = new HashSet<>();
                sessionSet.add(session);
                webSocketMap.put(funcType,sessionSet);
            }
        }

        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose(){
        webSocketMap=new ConcurrentHashMap<>();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }

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

    public static void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

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

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

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

    public static void setOnlineCount(int onlineCount) {
        WebSocket.onlineCount = onlineCount;
    }

    public static ConcurrentHashMap<String, Set<Session>> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, Set<Session>> webSocketMap) {
        WebSocket.webSocketMap = webSocketMap;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,String funcType) throws Exception {
        if(webSocketMap.containsKey(funcType)){
            Set<Session> sessionSet = webSocketMap.get(funcType);
            if(sessionSet!=null){
                for (Session session : sessionSet) {
                    if(session.getBasicRemote()!=null){
                        session.getBasicRemote().sendText(message);
                    }
                }
            }
        }else{
            log.error("订阅类型:"+funcType+",不存在!");
            throw new Exception("连接已关闭,请刷新页面后重试");
        }

    }

}

二、java代码调用,往websocker赋数据

复制代码
WebSocket.sendInfo(JSON.toJSONString("sdfasd232"),"3");

三、测试是否连接成功以及推送信息

四、前端代码处理

复制代码
/**
 * 初始化websocket连接
 */
function initWebSocket() {
	var websocket = null;
	if('WebSocket' in window) {
		websocket = new WebSocket("ws://127.0.0.1:8080/webSocket?funcType=3" );
	} else {
		alert("该浏览器不支持websocket!");
	}
	websocket.onopen = function(event) {
		console.log("建立连接");
		websocket.send('Hello WebSockets!');
	}
	websocket.onclose = function(event) {
		console.log('连接关闭')
		reconnect(); //尝试重连websocket
	}
	//建立通信后,监听到后端的数据传递
	websocket.onmessage = function(event) {
		let data = JSON.parse(event.data);
		//业务处理....
		if(data.step == 1){
		   alert(data.msg);
		}
	}
	websocket.onerror = function() {
		// notify.warn("websocket通信发生错误!");
		// initWebSocket()
	}
	window.onbeforeunload = function() {
		websocket.close();
	}
// 重连
function reconnect() {
	console.log("正在重连");
	// 进行重连
	setTimeout(function () {
		initWebSocket();
	}, 1000);
}
相关推荐
_F_y8 分钟前
C++重点知识总结
java·jvm·c++
打工的小王9 分钟前
Spring Boot(三)Spring Boot整合SpringMVC
java·spring boot·后端
毕设源码-赖学姐10 分钟前
【开题答辩全过程】以 高校体育场馆管理系统为例,包含答辩的问题和答案
java·spring boot
我真会写代码12 分钟前
SSM(指南一)---Maven项目管理从入门到精通|高质量实操指南
java·spring·tomcat·maven·ssm
vx_Biye_Design12 分钟前
【关注可免费领取源码】房屋出租系统的设计与实现--毕设附源码40805
java·spring boot·spring·spring cloud·servlet·eclipse·课程设计
java干货17 分钟前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法
_F_y17 分钟前
C语言重点知识总结(含KMP详细讲解)
c语言·开发语言
DN金猿18 分钟前
接口路径正确,请求接口却提示404
java·tomcat
毕设源码-郭学长18 分钟前
【开题答辩全过程】以 基于python的二手房数据分析与可视化为例,包含答辩的问题和答案
开发语言·python·数据分析
无小道41 分钟前
Qt——常用控件
开发语言·qt