`

spring+websocket整合学习笔记

阅读更多
    传统的B/S通讯方式都是基于客户端主动请求,服务端响应结果。有了websocket技术之后,就可以实现服务端主动向客户端推送数据了。因为websocket是html5的技术,需要支持html5的浏览器,以下例子我使用的是ie11和chrome61,均可以测试通过。
以下是集成spring的websocket例子:
1. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.gov.zjport.learning.redis</groupId>
  <artifactId>websocket</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>websocket Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
  	<spring-version>4.2.4.RELEASE</spring-version>
  </properties>
  <dependencies>
    <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>
<dependency>  
	<groupId>org.springframework</groupId>  
    <artifactId>spring-core</artifactId>  
    <version>${spring-version}</version>  
</dependency>  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-web</artifactId>  
    <version>${spring-version}</version>  
</dependency>  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>${spring-version}</version>  
</dependency>  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-context-support</artifactId>  
    <version>${spring-version}</version>  
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.6.6</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.6</version>
</dependency>

  </dependencies>
  <build>
    <finalName>websocket</finalName>
    <plugins>
		<plugin>
			<artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.7</source>
				<target>1.7</target>
			</configuration>
		</plugin>
	</plugins>
  </build>
</project>


2. 服务端java代码
package cn.gov.zjport.demo.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

  
public class WebsocketHandler extends TextWebSocketHandler {  
  
    @Override  
    protected void handleTextMessage(WebSocketSession session,  
            TextMessage message) throws Exception {  
        super.handleTextMessage(session, message);  
        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
        session.sendMessage(returnMessage);  
    }  
}


3.spring配置文件
beans.xml(这个文件是为了例子完整性添加的,跟websocket整合无关)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
	   <context:annotation-config />
	   <context:component-scan base-package="cn.gov.zjport.demo" />
</beans>

spring-websocket.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">

    <websocket:handlers>
        <websocket:mapping path="/springws/myhandler.ws" handler="myHandler" />
	</websocket:handlers>
    <bean id="myHandler" class="cn.gov.zjport.demo.websocket.WebsocketHandler" />
</beans>


4.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance  http://www.springmodules.org/schema/cache/springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/config/beans.xml</param-value>
	</context-param>
	
	 <listener>
   		 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
	    <servlet-name>dispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>classpath:config/spring/spring-websocket.xml</param-value>
	    </init-param>
	</servlet>
	<servlet-mapping>
	    <servlet-name>dispatcherServlet</servlet-name>
	    <url-pattern>*.ws</url-pattern>
	</servlet-mapping>
</web-app>


5.客户端html5页面
<!DOCTYPE html>  
<html>  
<head>  
    <title>WebSocket Echo demo</title>  
    <style type="text/css">  
        #connect-container {  
            float: left;  
            width: 400px  
        }  
  
        #connect-container div {  
            padding: 5px;  
        }  
  
        #console-container {  
            float: left;  
            margin-left: 15px;  
            width: 400px;  
        }  
  
        #console {  
            border: 1px solid #CCCCCC;  
            border-right-color: #999999;  
            border-bottom-color: #999999;  
            height: 170px;  
            overflow-y: scroll;  
            padding: 5px;  
            width: 100%;  
        }  
  
        #console p {  
            padding: 0;  
            margin: 0;  
        }  
    </style>  
  
    <script type="text/javascript">  
        var ws = null;  
        var url = null;  
        var transports = [];  
  
        function setConnected(connected) {  
            document.getElementById('connect').disabled = connected;  
            document.getElementById('disconnect').disabled = !connected;  
            document.getElementById('echo').disabled = !connected;  
        }  
  
        function connect() {
        	updateUrl("/websocket/springws/myhandler.ws");
            alert("url:"+url);  
            ws = new WebSocket(url);  
  
            ws.onopen = function () {  
                setConnected(true);  
                log('Info: connection opened.');  
            };  
            ws.onmessage = function (event) {  
                log('Received: ' + event.data);  
            };  
            ws.onclose = function (event) {  
                setConnected(false);  
                log('Info: connection closed.');  
                log(event);  
            };  
        }  
  
        function disconnect() {  
            if (ws != null) {  
                ws.close();  
                ws = null;  
            }  
            setConnected(false);  
        }  
  
        function echo() {  
            if (ws != null) {  
                var message = document.getElementById('message').value;  
                log('Sent: ' + message);  
                ws.send(message);  
            } else {  
                alert('connection not established, please connect.');  
            }  
        }  
  
        function updateUrl(urlPath) {  
             if (window.location.protocol == 'http:') {  
                 url = 'ws://' + window.location.host + urlPath;  
             } else {  
                 url = 'wss://' + window.location.host + urlPath;  
             }  
        }  
  
        function updateTransport(transport) {  
            alert(transport);  
          transports = (transport == 'all') ?  [] : [transport];  
        }  
          
        function log(message) {  
            var console = document.getElementById('console');  
            var p = document.createElement('p');  
            p.style.wordWrap = 'break-word';  
            p.appendChild(document.createTextNode(message));  
            console.appendChild(p);  
            while (console.childNodes.length > 25) {  
                console.removeChild(console.firstChild);  
            }  
            console.scrollTop = console.scrollHeight;  
        }  
    </script>  
</head>  
<body>  
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets   
    rely on Javascript being enabled. Please enable  
    Javascript and reload this page!</h2></noscript>  
<div>  
    <div id="connect-container">  
        <div>  
            <button id="connect" onclick="connect();">Connect</button>  
            <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>  
        </div>  
        <div>  
            <textarea id="message" style="width: 350px">Here is a message!</textarea>  
        </div>  
        <div>  
            <button id="echo" onclick="echo();" disabled="disabled">Echo message</button>  
        </div>  
    </div>  
    <div id="console-container">  
        <div id="console"></div>  
    </div>  
</div>  
</body>  
</html>  


6.访问http://localhost:8080/websocket/websocket.html

  • 大小: 40.7 KB
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    SpringBoot+SpringMVC+SrpingSecurity+SSM整合.zip

    在"SpringBoot+SpringMVC+SpringSecurity+SSM整合.zip"的学习笔记中,你可能会涉及以下几个关键知识点: 1. SpringBoot的起步依赖和自动配置:理解如何通过添加不同模块的starter依赖来引入所需的Spring功能,以及...

    Spring高级源码学习笔记.zip

    另外,Spring还提供了对WebSocket、RESTful API的支持,以及与各种企业级服务如消息队列、缓存的整合。源码研究这部分能帮助开发者更好地利用Spring构建分布式系统。 在阅读Spring源码笔记时,建议结合实际项目经验...

    SpringBoot经典学习笔记

    在"SpringBoot经典学习笔记"中,你可能会了解到以下关键知识点: 1. **起步依赖(Starter Dependencies)**:SpringBoot通过starter依赖来简化构建配置,比如`spring-boot-starter-web`用于Web应用,`spring-boot-...

    Spring-5.0.0-官方中文文档

    而"Maven3实战笔记(整合).pdf"则可以帮助开发者了解如何使用Maven这一强大的构建工具与Spring框架进行整合,实现自动化构建和依赖管理。 总的来说,Spring 5.0.0不仅在核心功能上进行了强化,还在反应式编程、Web...

    Spring高级四十九讲,spring5.rar

    Spring框架是Java后端开发中的核心组件,Spring 5作为其最新版本,引入了许多改进和新特性...文档中的"spring_bottom.rar"和"文档.rar"可能包含了详细的课程大纲、笔记或示例代码,是进一步学习和实践的重要参考资料。

    Springboot017学生读书笔记共享.zip

    【标题】"Springboot017学生读书笔记共享.zip"是一个与Spring Boot相关的学习资源压缩包,很可能是某个学生在学习Spring Boot框架的过程中积累的笔记和资料。Spring Boot是Java开发的一个流行框架,它简化了Spring的...

    Java Springboot入门自学笔记

    本入门自学笔记将带你一步步了解并掌握Spring Boot的核心概念和实践技巧。 ### 01 SpringBoot简介 #### 1.1 Spring Boot 的优势 - **简化的起步**:Spring Boot 提供了起步依赖(starter),可以通过添加相应的Maven...

    javaweb笔记

    这份"javaweb笔记"旨在为学习者提供一个全面而精炼的学习指南,帮助你在JavaWeb开发领域快速成长。下面将详细阐述其中涉及的核心概念和技术。 1. **Servlet**:Servlet是Java平台上的服务器端组件,用于处理HTTP...

    springbot实战笔记整理.zip

    在数据库集成方面,笔记详细阐述了SpringBoot与JPA(Java Persistence API)和MyBatis的整合。SpringData JPA提供了对ORM(对象关系映射)的高级支持,简化了数据库操作;而MyBatis则是一种轻量级的SQL映射框架,...

    spring4:崔范均的春天4

    《Spring4:崔范均的春天4》...该教程的"spring4-master"目录可能包含了源码、示例项目、笔记等内容,为深入学习提供了实践基础。通过动手实践,开发者能更深刻地理解Spring4的强大功能,并将其应用于实际工作场景中。

    springboot.zip全套学习资源(对应B站课程)

    5. **数据访问**:学习如何整合JDBC、MyBatis或Hibernate进行数据库操作,包括配置数据源、事务管理等。 6. **Spring Data JPA**:了解如何使用Spring Data JPA简化CRUD操作,以及Repository接口的使用。 7. **...

    尚硅谷SpringMVC源码及PPT

    - 整合其他技术,如MyBatis、WebSocket等 通过尚硅谷的SpringMVC源码分析,开发者可以更深入地了解SpringMVC的内部机制,如DispatcherServlet、HandlerAdapter、ModelAndView的实现细节,以及AOP、IOC容器在...

    GuliOnline:Springboot在线教育项目

    【GuliOnline:Springboot在线教育...GuliOnline项目通过整合这些技术,构建了一个完整的在线教育平台,覆盖了用户注册登录、课程浏览、在线学习、交流互动等多个功能模块,展示了SpringBoot在实际项目中的强大能力。

    毕业设计:基于SpringBoot的在线教育系统.zip

    4. 在线学习:提供播放视频、查看文档、做笔记等学习功能,可能利用WebSocket实现实时交互。 5. 讨论区:允许用户提问和回答,涉及论坛或社交网络功能的实现。 6. 作业与测试:创建、提交和批改作业,实现在线测试和...

Global site tag (gtag.js) - Google Analytics