具体细节可参考文档:WebSocket官网
4.0.2.RELEASE
org.springframework
spring-websocket
${spring.version}
org.springframework
spring-messaging
${spring.version}
其中命名空间
xmlns:websocket="http://www.springframework.org/schema/websocket"
以及引入的功能
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd
关于头部解释可参考xml头部解释
官方Spring API
package com.websocket;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
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 com.alibaba.fastjson.JSONObject;
import com.util.RandomUtils;
//创建websocket处理类
public class WebsocketEndPoint extends TextWebSocketHandler {
private Timer timer;
private Logger logger=Logger.getLogger(WebsocketEndPoint.class);
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
TextMessage returnMessage=new TextMessage("服务端返回报文:"+message.getPayload());
session.sendMessage(returnMessage);
super.handleTextMessage(session, message);
}
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
logger.info("连接建立后处理方法");
timer=new Timer(true);
LoadDataTask task=new LoadDataTask(session);
timer.schedule(task,1000,1000);
super.afterConnectionEstablished(session);
}
@Override
public void handleTransportError(WebSocketSession session,
Throwable exception) throws Exception {
logger.info("抛出异常时处理方法");
super.handleTransportError(session, exception);
}
@Override
public void afterConnectionClosed(WebSocketSession session,
CloseStatus status) throws Exception {
if(!session.isOpen()){
logger.info("连接已关闭");
timer.cancel();
}
logger.info("连接关闭后处理方法");
super.afterConnectionClosed(session, status);
}
//内部类实现数据获取
class LoadDataTask extends TimerTask{
private WebSocketSession session;
public WebSocketSession getSession() {
return session;
}
public void setSession(WebSocketSession session) {
this.session = session;
}
public LoadDataTask() {
super();
}
public LoadDataTask(WebSocketSession session) {
super();
this.session = session;
}
@Override
public void run() {
Set set=RandomUtils.getInfo(6);//生成一个随机数set
String jsonObject=JSONObject.toJSONString(set);
TextMessage textMessage = new TextMessage(jsonObject);
try {
handleTextMessage(session, textMessage);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(),e);
}
}
}
}
package com.websocket;
import java.util.Map;
import org.apache.log4j.Logger;
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;
//创建握手(handshake)接口 WebSocket拦截器
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
private Logger logger=Logger.getLogger(HandshakeInterceptor.class);
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
logger.info("创建握手后...");
super.afterHandshake(request, response, wsHandler, ex);
}
@Override
public boolean beforeHandshake(ServerHttpRequest arg0,
ServerHttpResponse arg1, WebSocketHandler arg2,
Map arg3) throws Exception {
logger.info("握手完成前...");
return super.beforeHandshake(arg0, arg1, arg2, arg3);
}
}
package com.websocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//支持websocket
registry.addHandler(new WebsocketEndPoint(),"/websocket/socketServer.do").addInterceptors(new HandshakeInterceptor());
//支持sockjs
registry.addHandler(new WebsocketEndPoint(),"/sockjs/socketServer.do").addInterceptors(new HandshakeInterceptor()).withSockJS();
}
}
注:该类需要放在SpringMVC扫描路径下
@Configuration 指明该类为Spring配置类
@EnableWebSocket 声明该类支持WebSocket
说明: 网上有很多文章配置中添加了一个注解@EnableWebMvc和继承了WebMvcConfigurerAdapter,其中@EnableWebMVC注解用来开启Web MVC的配置支持.相当于DispatcherServlet context内使用
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
WebSocket