SpringMVC+HTML5+websocket即时聊天Demo

websocket的通信形式今天刚学,好处就不说了,网上有很多,下面把写的即时通信的demo记录下来,运行出来像下面一样:


SpringMVC+HTML5+websocket即时聊天Demo_第1张图片
 一、spring必须4.0以上,maven的pom文件如下:

 

		
			org.springframework
			spring-orm
			4.2.4.RELEASE
		
		
			org.springframework
			spring-webmvc
			4.2.4.RELEASE
		

		
			org.springframework
			spring-websocket
			4.2.4.RELEASE
		
		
			org.springframework
			spring-messaging
			4.2.4.RELEASE
		

当然了,还有servlet等等了。。。那些就自己查了

 

二、spring中,关于websocket的配置:

 

	

	
		
		
			
		
	

 不要忘记引入xsd文件,

 

 

http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd

 整个关于websocket的配置文件如下:

 

 



	
	

	
		
		
			
		
	

 三、Interceptor类

 

 

package com.wang.test.websocket.demo;

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

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor{
	// 初次握手访问前
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse,
			WebSocketHandler webSocketHandler, Map map) throws Exception {
		if (request instanceof ServletServerHttpRequest) {
			HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
			String userName = "xq";
			// 使用userName区分WebSocketHandler,以便定向发送消息
			// String userName = (String)
			// session.getAttribute("WEBSOCKET_USERNAME");
			map.put("WEBSOCKET_USERNAME", userName);
			servletRequest.getSession().setAttribute("WEBSOCKET_USERNAME", userName);
		}
		return true;
	}

	// 初次握手访问后
	@Override
	public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
			WebSocketHandler webSocketHandler, Exception e) {

	}
}

 四、WebSocketHander类

 

 

package com.wang.test.websocket.demo;

import org.apache.log4j.Logger;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;

public class WebSocketHander implements WebSocketHandler {
	
	private static final Logger logger = Logger.getLogger(WebSocketHander.class);

	private static final ArrayList users = new ArrayList<>();

	// 初次链接成功执行
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("链接成功......");
		users.add(session);
		String userName = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
		if (userName != null) {
			// 查询未读消息
			int count = 5;
			session.sendMessage(new TextMessage(count + ""));
		}
	}

	// 接受消息处理消息
	@Override
	public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage webSocketMessage)
			throws Exception {
		sendMessageToUsers(new TextMessage(webSocketMessage.getPayload() + ""));
	}

	@Override
	public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
		if (webSocketSession.isOpen()) {
			webSocketSession.close();
		}
		logger.debug("链接出错,关闭链接......");
		users.remove(webSocketSession);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
		logger.debug("链接关闭......" + closeStatus.toString());
		users.remove(webSocketSession);
	}

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

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) {
		for (WebSocketSession user : users) {
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(String userName, TextMessage message) {
		for (WebSocketSession user : users) {
			if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
				try {
					if (user.isOpen()) {
						user.sendMessage(message);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}
}

 五、页面显示文件:

 

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>














webSocket测试





	
	

 六、参考:http://blog.csdn.net/mr_zhuqiang/article/details/46618197  把这里面配置形式改了

 七、代码地址:https://github.com/hejiawang/SSMTest

 

 

你可能感兴趣的:(Spring)