1、要求
spring框架版本4.0以上
2、添加jar包
核心包
spring-websocket-4.1.4.RELEASE.jar
spring-messaging-4.1.4.RELEASE.jar
依赖包(如果项目已添加,则不用重复添加)
spring-beans-4.1.4.RELEASE.jar
spring-context-4.1.4.RELEASE.jar
spring-core-4.1.4.RELEASE.jar
spring-web-4.1.4.RELEASE.jar
或者在maven的pom.xml中加入websocket所依赖的jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>4.0.1.RELEASE</version> </dependency>
3、创建握手类
package org.kent.socket.interceptor; 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 boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { super.afterHandshake(request, response, wsHandler, ex); } }4、创建处理类
package org.kent.socket.handler; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; @Component public class WebsocketEndPoint extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); TextMessage returnMessage = new TextMessage(message.getPayload()+" hello world!"); session.sendMessage(returnMessage); } }
5、处理类和握手协议的spring配置(applicationContext.xml文件)
<websocket:handlers> <websocket:mapping path="/sockets/websocketEndPoint" handler="websocketEndPoint"/> <websocket:handshake-interceptors> <bean class="org.kent.socket.HandshakeInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers>