零配置只需三步搞定ssm框架整合socket

我使用的是不需要在xml中进行配置的方法 ,只在socket类上面加注解完成整合。

1.创建websocket配置类,WebSocketConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
	@Autowired
	SpringWebSocketHandler handler;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		// 添加websocket处理器,添加握手拦截器
		registry.addHandler(handler, "/websocket").addInterceptors(new HttpSessionHandshakeInterceptor());

		// 添加websocket处理器,添加握手拦截器
		//如果在不支持websocket的浏览器中,会自动降为轮询的方式。 
		registry.addHandler(handler, "/ws/sockjs").addInterceptors(new HttpSessionHandshakeInterceptor()).withSockJS();

	}
}

2.创建握手处理类SpringWebSocketHandler.java

package com.gdjk.dems.socket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * 
 * 
 * @Title: SpringWebSocketHandler.java
 * @Description: 处理类  
 * @author RBJ created by2019年2月15日 下午7:05:21
 * @version 1.0
 *
 */
@Repository
public class SpringWebSocketHandler extends TextWebSocketHandler {
	protected static final Logger logger = LoggerFactory.getLogger(SpringWebSocketHandler.class);
	private static final Map users;

	static {
		users = new HashMap();
	}

	public SpringWebSocketHandler() {
	}

	/**
	 * 连接成功时候,会触发页面上onopen方法
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String username = (String) session.getAttributes().get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME);
		users.put(username, session);
		System.out.println("用户id:" + username + "已链接!..............................");
		System.out.println("连接数当前数量:" + users.size() + "..............................");
		// 这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户
		// session.sendMessage(returnMessage);
		// 给所有人发送在线人数
		// sendMessageToUsers(new TextMessage(String.valueOf(users.size())));
	}

	/**
	 * 关闭连接时触发
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.debug("websocket connection closed......");
		String username = (String) session.getAttributes().get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME);
		System.out.println("用户id:" + username + "已退出!.....................");
		users.remove(username);
		System.out.println("剩余在线用户" + users.size() + ".............................");
		sendMessageToUsers(new TextMessage(String.valueOf(users.size())));
	}

	/**
	 * js调用websocket.send时候,会调用该方法
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		// sendMessageToUser(username, message);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			// session.close();
		}
		String username = (String) session.getAttributes().get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME);
		logger.debug("websocket connection closed......");
		users.remove(username);
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(String userName, TextMessage message) throws IOException {
		WebSocketSession webSocketSession = users.get(userName);
		if (webSocketSession != null) {
			System.out.println(webSocketSession.getUri());
			webSocketSession.sendMessage(message);
			System.out.println("已发送.............................");
		} else {

			System.out.println("用户不在线.............................");

		}
	}

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) throws IOException {
		Iterator iter = users.values().iterator();
		while (iter.hasNext()) {
			iter.next().sendMessage(message);

		}
	}



}

3.创建页面的socket.js处理

//websocket连接
$(function() {

	var url = window.location.host;
	console.log('连接端口' + url);
    //dems为我的项目名称,需要替换成你自己的项目名称
	if ('WebSocket' in window) {
		websocket = new WebSocket("ws://" + url + "/dems/websocket");
	} else {
	    websocket = new SockJS("http://" + url + "/dems/ws/sockjs");
	}
	websocket.onopen = onOpen;
	websocket.onmessage = onMessage;
	websocket.onerror = onError;
	websocket.onclose = onClose;
	var t1 ;
	function onOpen(openEvt) {
		console.log('websocket已连接')
	}
	function onMessage(evt) {
		console.log('websocket接收' + evt.data)

	}
	function onError() {
		console.log('websocket服务器错误')
	}
	function onClose() {
		console.log('websocket服务器已断开连接');


	}
	

	function doSend() {
		if (websocket.readyState == websocket.OPEN) {
			var msg = document.getElementById("inputMsg").value;
			websocket.send(msg);// 调用后台handleTextMessage方法
			alert("发送成功!");
		} else {
			alert("连接失败!");
		}
	}
});

4.运行项目查看是否连接

控制台信息

网页控制台输出

零配置只需三步搞定ssm框架整合socket_第1张图片

至此,socket已经集成进去了,如果需要controller发送消息给网页,控制器应该使用下面方法,调用SpringWebSocketHandler 类里面的方法进行消息的发送,发送后socket.js就会进行消息的接收,我们就可以进行处理了。方法的用户名username为我们的SESSIONID,因为HttpSessionHandshakeInterceptor 源码是默认把sessionId存为username的,如果不想用sessionid,那么就实现自己的HttpSessionHandshakeInterceptor类。列如可以在登陆后把唯一的用户名作为唯一标识。

零配置只需三步搞定ssm框架整合socket_第2张图片

有问题请大家联系我哈qq 1406423298。

你可能感兴趣的:(框架集,websocket)