Spring WebSocket配置说明以及方法功能作用和执行顺序以及群发消息的调用

Spring版本5.0

xml配置


	
	
		/websocket" handler="websocket"/>
		
			
		
	/websocket" handler="websocket"/>
		
			
		
	

注:前端ws协议请求项目根目录下配置的/websocket即可,上方代码块蓝色部分配置的路径

客户端代码(JS版)


    
    

 

 

 

 

 

代码逻辑:

配置好拦截器类和socket握手类,然后在前端请求socket地址的时候这两个类的方法就会对应的执行,并且获取到SocketSession(看成session就行了),SocketSession有sendMessage()方法用于发送消息到每个客户端,而TextWebSocketHandler的子类中的handleMessage()方法和handleTextMessage()用于接收客户端发送的消息,一来一回就实现了双工通信。

拦截器HttpSessionHandshakeInterceptor子类类代码:

package com.share.common.socket;

import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		// TODO Auto-generated method stub
		super.afterHandshake(request, response, wsHandler, ex);
	}
	@Override
	public boolean beforeHandshake(ServerHttpRequest arg0,
			ServerHttpResponse arg1, WebSocketHandler arg2,
			Map arg3) throws Exception {
		// TODO Auto-generated method stub
		return super.beforeHandshake(arg0, arg1, arg2, arg3);
	}
}

握手类TextWebSocketHandler子类代码:

package com.share.common.socket;

import com.google.common.collect.Maps;
import com.share.task.SignedClearTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;

public class WebsocketEndPoint extends TextWebSocketHandler {
	private static Map SESSION_MAP= Maps.newConcurrentMap();
	private final static Logger logger= LogManager.getLogger(SignedClearTask.class);

	/**
	 * 每次接收到消息执行2
	 * @param session
	 * @param message
	 * @throws Exception
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session,
			TextMessage message) throws Exception {
		// TODO Auto-generated method stub
		logger.debug("Method for handleTextMessage");
		super.handleTextMessage(session, message);
	}

	/**
	 * 每次收到消息执行1
	 * @param session
	 * @param message
	 * @throws Exception
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
		logger.debug("Method for handleMessage");
		super.handleMessage(session, message);
	}

	/**
	 * socket连接断开执行
	 * @param session
	 * @param status
	 * @throws Exception
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		logger.debug("Method for afterConnectionClosed");
		SESSION_MAP.remove(session.getId());
		super.afterConnectionClosed(session, status);
	}

	/**
	 * socket连接执行2
	 * @param session
	 * @throws Exception
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("Method for afterConnectionEstablished");
		SESSION_MAP.put(session.getId(),session);//把连接的用户session存入SESSION_MAP
		super.afterConnectionEstablished(session);
	}

	/**
	 * socket连接执行1
	 * @return
	 */
	@Override
	public boolean supportsPartialMessages() {
		logger.debug("Method for supportsPartialMessages");
		return super.supportsPartialMessages();
	}

	/**
	 * 自定义群发消息方法
	 * @param msg
	 */
	public void sendAllSessionMessage(String msg){
		for (WebSocketSession session:SESSION_MAP.values()){
			try {
				session.sendMessage(new TextMessage(msg));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

其他地方要使用群发的时候直接调用群发方法sendAllSessionMessage()即可

两个类的方法执行顺序思维导图如下:

Spring WebSocket配置说明以及方法功能作用和执行顺序以及群发消息的调用_第1张图片

群发消息调用(可以在系统的任何地方调用,例如:controller中调用)

WebsocketEndPoint websocketEndPoint=new WebsocketEndPoint();
websocketEndPoint.sendAllSessionMessage("send all user test");

如果要单独针对某个用户发送socket消息,那么就需要你对保存的连接的session做记录了

注:代码直接复制改改包名即可使用,但还是了解执行顺序及作用才能使用得得心应手

你可能感兴趣的:(Java,Spring)