热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringMVC自学杂记(四)--Spring+SpringMVC+WebSocket

1、WebSocket简介WebSocket是HTML5提供的一种全双工通信的协议,通常是浏览器(或其他客户端)与Web服务器之间的通信。这使得它适合于高度交互的Web应用程序,如及时通讯聊天

1、WebSocket简介

WebSocket是HTML5提供的一种全双工通信的协议,通常是浏览器(或其他客户端)与Web服务器之间的通信。这使得它适合于高度交互的Web应用程序,如及时通讯聊天等。

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——可以通俗的解释为服务器主动发送信息给客户端。

WebSocket首次在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符。[1] WebSocket通信协议于2011年被IETF定为标准RFC 6455,并被RFC7936所补充规范。

摘抄来自:百度百科-websocket


2、Spring+websocket

spring4.0已经就支持websocket了,可以去查看官网。

官网:spring websocket

注:这个spring+websocket,自己也不是很熟悉,只是最近使用到了,学习了一下,记录处理了,方便以后避免走更多的绕路。


3、配置环境

3.1、环境:

    spring-4.0.2.RELEASE
java1.7
apache-tomcat-7.0.75

maven构建工程:

POM.xml:


<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.3.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.3.0version>
dependency>

SpringMVC:

        
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.0.2.RELEASEversion>
dependency>

<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>4.0.2.RELEASEversion>
dependency>

WebSocket:

        
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-websocketartifactId>
<version>4.0.2.RELEASEversion>
dependency>

<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-messagingartifactId>
<version>4.0.2.RELEASEversion>
dependency>

3.2、Servlet-api

servlet-api必须是3.0+,才支持websocket,所以如果不是,则要更新jar包。

    <dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>

3.3、web.xml配置

并且 web.xml的namespace也要确保是3.0+,

web.xml

 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">



<absolute-ordering />
web-app>

代码:也要添加在web.xml开始。


并且必须将所以的filter和servlet都要添加异步:

<async-supported>trueasync-supported>

如:springMVC在web.xml中的配置也要添加:

    

<servlet>
<servlet-name>springMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>

<servlet-mapping>
<servlet-name>springMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>


4、service服务端的具体实现

4.1、首先创建websocket的处理类

MyWebSocketHandler.java

package com.cuit.secims.mw.ws;

import java.util.ArrayList;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;




public class MyWebSocketHandler implements WebSocketHandler{


private static final Logger log = Logger.getLogger(MyWebSocketHandler.class);

// 保存所有的用户session
private static final ArrayList users = new ArrayList();


// 连接 就绪时
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {

log.info("connect websocket success.......");

users.add(session);

}


// 处理信息
@Override
public void handleMessage(WebSocketSession session,
WebSocketMessage message) throws Exception {

Gson gson = new Gson();

// 将消息JSON格式通过Gson转换成Map
// message.getPayload().toString() 获取消息具体内容
Map msg = gson.fromJson(message.getPayload().toString(),
new TypeToken>() {}.getType());

log.info("handleMessage......."+message.getPayload()+"..........."+msg);

// session.sendMessage(message);

// 处理消息 msgContent消息内容
TextMessage textMessage = new TextMessage(msg.get("msgContent").toString(), true);
// 调用方法(发送消息给所有人)
sendMsgToAllUsers(textMessage);


}


// 处理传输时异常
@Override
public void handleTransportError(WebSocketSession session,
Throwable exception) throws Exception {
// TODO Auto-generated method stub

}



// 关闭 连接时
@Override
public void afterConnectionClosed(WebSocketSession session,
CloseStatus closeStatus) throws Exception {

log.info("connect websocket closed.......");

users.remove(session);

}



@Override
public boolean supportsPartialMessages() {
// TODO Auto-generated method stub
return false;
}



// 给所有用户发送 信息
public void sendMsgToAllUsers(WebSocketMessage message) throws Exception{

for (WebSocketSession user : users) {
user.sendMessage(message);
}

}

}

处理类可以实现WebSocketHandler最基本的接口,也可以实现具体的接口
如:这里写图片描述

处理类就是处理:连接开始、关闭、处理信息等方法


4.2、创建握手(handshake)接口/拦截器

HandshakeInterceptor .java

package com.cuit.secims.mw.ws;

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 attributes) throws Exception {

System.out.println("++++++++++++++++ HandshakeInterceptor: beforeHandshake ++++++++++++++"+attributes);

return super.beforeHandshake(request, response, wsHandler, attributes);
}



// 握手后
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {


System.out.println("++++++++++++++++ HandshakeInterceptor: afterHandshake ++++++++++++++");


super.afterHandshake(request, response, wsHandler, ex);
}

}

这个的主要作用是可以在握手前做一些事,把所需要的东西放入到attributes里面,然后可以在WebSocketHandler的session中, 取到相应的值,具体可参考HttpSessionHandshakeInterceptor,这儿也可以实现HandshakeInterceptor 接口。


4.3、注册处理类及握手接口

这个有两种方式:

  1. 创建一个类来实现注册
  2. 使用xml配置文件实现

4.3.1、创建类MyWebSocketConfig

package com.cuit.secims.mw.ws;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
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
@EnableWebMvc
@EnableWebSocket
public class MyWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {


@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

//前台 可以使用websocket环境
registry.addHandler(myWebSocketHandler(),"/websocket").addInterceptors(new HandshakeInterceptor());


//前台 不可以使用websocket环境,则使用sockjs进行模拟连接
registry.addHandler(myWebSocketHandler(), "/sockjs/websocket").addInterceptors(new HandshakeInterceptor())
.withSockJS();
}


// websocket 处理类
@Bean
public WebSocketHandler myWebSocketHandler(){
return new MyWebSocketHandler();
}


}

注意:不要忘记在springmvc的配置文件中配置对此类的自动扫描

<context:component-scan base-package="com.cuit.secims.mw.ws" />

4.3.2、xml配置方式

spring-WebSocket.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-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/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd"
>





<bean id="myHandler" class="com.cuit.secims.mw.ws.MyWebSocketHandler"/>


<bean id="myInterceptor" class="com.cuit.secims.mw.ws.HandshakeInterceptor"/>

<websocket:handlers >
<websocket:mapping path="/websocket" handler="myHandler"/>
<websocket:handshake-interceptors>
<ref bean="myInterceptor"/>
websocket:handshake-interceptors>
websocket:handlers>


<websocket:handlers>
<websocket:mapping path="/sockjs/websocket" handler="myHandler"/>
<websocket:handshake-interceptors>
<ref bean="myInterceptor"/>
websocket:handshake-interceptors>
<websocket:sockjs />
websocket:handlers>

beans>

其中就是对sockJS的注册方式。

注意:xml的namespace中要添加spring对websocket的支持:


<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-4.0.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd"
>


5、client客户端的实现

5.1、页面展示

index.html


<html>

<head>
<title>首页title>

<meta charset="utf-8">
<meta name="viewport" content=">
<meta name="renderer" content="webkit">


<script type="text/Javascript" src="jquery.min.js">script>


<script type="text/Javascript" src="sockjs.min.js" >script>


<script type="text/Javascript" src="index.js">script>

head>

<body>


<div style="margin: 20px auto; border: 1px solid blue; width: 300px; height: 500px;">


<div id="msg" style="width: 100%; height: 70%; border: 1px solid yellow;overflow: auto;">div>


<textarea id="tx" style="width: 100%; height: 20%;">textarea>


<button id="TXBTN" style="width: 100%; height: 8%;">发送数据button>

div>


body>

html>

5.2、JS-客户端主要的实现

index.js


$(function() {

var websocket;


// 首先判断是否 支持 WebSocket
if('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/SECIMS/websocket");
} else if('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/SECIMS/websocket");
} else {
websocket = new SockJS("http://localhost:8080/SECIMS/sockjs/websocket");
}

// 打开时
websocket.Onopen= function(evnt) {
console.log(" websocket.onopen ");
};


// 处理消息时
websocket.Onmessage= function(evnt) {
$("#msg").append("

(" + evnt.data + ")

"
);
console.log(" websocket.onmessage ");
};


websocket.Onerror= function(evnt) {
console.log(" websocket.onerror ");
};

websocket.Onclose= function(evnt) {
console.log(" websocket.onclose ");
};


// 点击了发送消息按钮的响应事件
$("#TXBTN").click(function(){

// 获取消息内容
var text = $("#tx").val();

// 判断
if(text == null || text == ""){
alert(" content can not empty!!");
return false;
}

var msg = {
msgContent: text,
postsId: 1
};

// 发送消息
websocket.send(JSON.stringify(msg));

});


});

客户端的主要API就是 创建websocket、监听打开、关闭、发送信息、处理信息等方法。

websocket = new WebSocket("ws://localhost:8080/SECIMS/websocket");

如果环境不支持websocket,则使用sockJS来模拟连接实现

websocket = new SockJS("http://localhost:8080/SECIMS/sockjs/websocket");

其中:SECIMS是工程名,而/websocket是环境支持,则请求的连接。而/sockjs/websocket,则是不支持websocket,使用sockJS模拟实现的连接。


6、效果展现

用户A:
这里写图片描述

用户B:
这里写图片描述


推荐阅读
  • Struts与Spring框架的集成指南
    本文详细介绍了如何将Struts和Spring两个流行的Java Web开发框架进行整合,涵盖从环境配置到代码实现的具体步骤。 ... [详细]
  • 深入解析 Apache Shiro 安全框架架构
    本文详细介绍了 Apache Shiro,一个强大且灵活的开源安全框架。Shiro 专注于简化身份验证、授权、会话管理和加密等复杂的安全操作,使开发者能够更轻松地保护应用程序。其核心目标是提供易于使用和理解的API,同时确保高度的安全性和灵活性。 ... [详细]
  • ssm框架整合及工程分层1.先创建一个新的project1.1配置pom.xml ... [详细]
  • Spring Boot 中静态资源映射详解
    本文深入探讨了 Spring Boot 如何简化 Web 应用中的静态资源管理,包括默认的静态资源映射规则、WebJars 的使用以及静态首页的处理方法。通过本文,您将了解如何高效地管理和引用静态资源。 ... [详细]
  • 本文探讨了 Spring Boot 应用程序在不同配置下支持的最大并发连接数,重点分析了内置服务器(如 Tomcat、Jetty 和 Undertow)的默认设置及其对性能的影响。 ... [详细]
  • Java项目分层架构设计与实践
    本文探讨了Java项目中应用分层的最佳实践,不仅介绍了常见的三层架构(Controller、Service、DAO),还深入分析了各层的职责划分及优化建议。通过合理的分层设计,可以提高代码的可维护性、扩展性和团队协作效率。 ... [详细]
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 作为一名新手,您可能会在初次尝试使用Eclipse进行Struts开发时遇到一些挑战。本文将为您提供详细的指导和解决方案,帮助您克服常见的配置和操作难题。 ... [详细]
  • 本文探讨了如何在 PHP 的 Eloquent ORM 中实现数据表之间的关联查询,并通过具体示例详细解释了如何将关联数据嵌入到查询结果中。这不仅提高了数据查询的效率,还简化了代码逻辑。 ... [详细]
  • 探讨如何真正掌握Java EE,包括所需技能、工具和实践经验。资深软件教学总监李刚分享了对毕业生简历中常见问题的看法,并提供了详尽的标准。 ... [详细]
  • 本文探讨了如何在日常工作中通过优化效率和深入研究核心技术,将技术和知识转化为实际收益。文章结合个人经验,分享了提高工作效率、掌握高价值技能以及选择合适工作环境的方法,帮助读者更好地实现技术变现。 ... [详细]
  • 本文介绍了如何利用 Spring Boot 和 Groovy 构建一个灵活且可扩展的动态计算引擎,以满足钱包应用中类似余额宝功能的推广需求。我们将探讨不同的设计方案,并最终选择最适合的技术栈来实现这一目标。 ... [详细]
  • 本文介绍了一个基于 Java SpringMVC 和 SSM 框架的综合系统,涵盖了操作日志记录、文件管理、头像编辑、权限控制、以及多种技术集成如 Shiro、Redis 等,旨在提供一个高效且功能丰富的开发平台。 ... [详细]
  • MySQL 数据库迁移指南:从本地到远程及磁盘间迁移
    本文详细介绍了如何在不同场景下进行 MySQL 数据库的迁移,包括从一个硬盘迁移到另一个硬盘、从一台计算机迁移到另一台计算机,以及解决迁移过程中可能遇到的问题。 ... [详细]
author-avatar
glh3112259
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有