您好,登录后才能下订单哦!
本篇文章给大家分享的是有关使用webSocket与spring怎么实现一个应用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
<properties>
<!-- spring版本号 -->
<spring.version>4.0.2.RELEASE</spring.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
2 sping配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:websocket="http://www.springframework.org/schema/websocket" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd"> <!-- 组件扫描器 --> <context:component-scan base-package="com.gaofei.controller" /> <!-- 注解驱动 --> <mvc:annotation-driven /> <!-- 静态资源映射 --> <mvc:resources location="/WEB-INF/js/" mapping="/js/**" /> <mvc:resources location="/WEB-INF/css/" mapping="/css/**" /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- websocket处理类 --> <bean id="websocketEndPoint" class="com.gaofei.controller.WebsocketEndPoint"/> <websocket:handlers> <websocket:mapping handler="websocketEndPoint" path="/websocket/socketServer.do"/> <websocket:handshake-interceptors> <bean class="com.gaofei.controller.HandInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers> <!-- 注册 sockJS 采用http协议的 --> <websocket:handlers> <websocket:mapping handler="websocketEndPoint" path="/sockjs/websokect.ws"/> <websocket:handshake-interceptors> <bean class="com.gaofei.controller.HandInterceptor"/> </websocket:handshake-interceptors> <websocket:sockjs /> </websocket:handlers> </beans>
其中命名空间
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
package com.gaofei.controller; 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; public class WebsocketEndPoint extends TextWebSocketHandler { private Timer timer; private Logger logger=Logger.getLogger(WebsocketEndPoint.class); @Override protected void handleTextMessage(WebSocketSession session,//session中携带http请求报文信息 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 {//握手成功后,启动一个定时器timer logger.info("连接建立后处理方法"); timer=new Timer(true); LoadDataTask task=new LoadDataTask(session); timer.schedule(task,1000,1000);//1s执行一次任务 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 {//连接关闭后 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) {//系统将当前建立连接后的session传递给内部类的session,达到session共享 super(); this.session = session; } @Override public void run() {//启动多线程 int i=0; String taskCommand="定时执行任务"+ ++i; TextMessage textMessage = new TextMessage(taskCommand); try { handleTextMessage(session, textMessage);//定时调用handleTextMessage方法,向前端发送信息 } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(),e); } } } }
package com.gaofei.controller; 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.HandshakeInterceptor; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; /** * 拦截器(握手) */ public class HandInterceptor 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<String, Object> arg3) throws Exception { logger.info("握手完成前..."); return super.beforeHandshake(arg0, arg1, arg2, arg3); } }
package com.gaofei.controller; 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; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { //支持websocket registry.addHandler(new WebsocketEndPoint(),"/websocket/socketServer.do").addInterceptors(new HandInterceptor()); //支持sockjs registry.addHandler(new WebsocketEndPoint(),"/sockjs/socketServer.do").addInterceptors(new HandInterceptor()).withSockJS(); } }
注:该类需要放在SpringMVC扫描路径下
@Configuration 指明该类为Spring配置类
@EnableWebSocket 声明该类支持WebSocket
说明: 网上有很多文章配置中添加了一个注解@EnableWebMvc和继承了WebMvcConfigurerAdapter,其中@EnableWebMVC注解用来开启Web MVC的配置支持.相当于DispatcherServlet context内使用<mvc:annotation-driven>元素,WebMvcConfigurerAdapter配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制.
XML配置模式:
<!-- websocket处理类 --> <bean id="websocketEndPoint" class="com.gaofei.controller.WebsocketEndPoint"/> <websocket:handlers> <websocket:mapping handler="websocketEndPoint" path="/websocket/socketServer.do"/> <websocket:handshake-interceptors> <bean class="com.gaofei.controller.HandInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers> <!-- 注册 sockJS 采用http协议的 --> <websocket:handlers> <websocket:mapping handler="websocketEndPoint" path="/sockjs/websokect.ws"/> <websocket:handshake-interceptors> <bean class="com.gaofei.controller.HandInterceptor"/> </websocket:handshake-interceptors> <websocket:sockjs /> </websocket:handlers>
<!DOCTYPE> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>WebSocket</title> </head> <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> //加载websocket数据 function WebSocketTest(){ if ("WebSocket" in window){ alert("您的浏览器支持 WebSocket!"); // 打开一个 web socket var ws = new WebSocket("ws://localhost:8080/webSocketServer/websocket/socketServer.do"); ws.onopen = function(){ // Web Socket 已连接上,使用 send() 方法发送数据 ws.send("发送数据"); alert("数据发送中..."); }; ws.onmessage = function (evt){ var received_msg = evt.data; console.log(received_msg); }; ws.onclose = function(){ // 关闭 websocket alert("连接已关闭..."); }; } } </script> <body> <div id="sse"> <a href="javascript:WebSocketTest()">运行 WebSocket</a> </div> </body> </html>
以上就是使用webSocket与spring怎么实现一个应用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。