spring-websocket的搭建
Posted joe立
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring-websocket的搭建相关的知识,希望对你有一定的参考价值。
Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7
spring4.0以后加入了对websocket技术的支持,撸主目前的项目用的是SSM(springMVC+spring+MyBatis)框
架,所 以肯定要首选spring自带的websocket
1 在maven的pom.xml中加入websocket所依赖的jar包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
2 更新web.xml中namespace.xsd的版本
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
处理类和握手协议的spring配置(applicationContext.xml文件)
<bean id="websocket" class="com.xl.websocket.WebsocketEndPoint"/>
<websocket:handlers>
<websocket:mapping path="/websocket" handler="websocket"/>
<websocket:handshake-interceptors>
<bean class="com.up.websocket.HandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
3 创建握手(handshake)接口
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
System.out.println("Before Handshake");
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
System.out.println("After Handshake");
super.afterHandshake(request, response, wsHandler, ex);
}
}
4 创建websocket处理类
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()+" 收到");
session.sendMessage(returnMessage);
}
}
以上是关于spring-websocket的搭建的主要内容,如果未能解决你的问题,请参考以下文章
spring-websocket 的 RestTemplateXhrTransport 工作吗?
Spring-Websockets 4.2 中使用 SockJS 的部分消息
如何使用 Spring-websocket 拒绝基于用户权限的主题订阅