一、spring配置文件Java代码

  1. <?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:tx="http://www.springframework.org/schema/tx"
  • xmlns:context="http://www.springframework.org/schema/context"
  • xmlns:mvc="http://www.springframework.org/schema/mvc"
  • xmlns:p="http://www.springframework.org/schema/p"
  • 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.1.xsd
  • http://www.springframework.org/schema/tx
  • http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
  • http://www.springframework.org/schema/context
  • http://www.springframework.org/schema/context/spring-context-4.1.xsd
  • http://www.springframework.org/schema/mvc
  • http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
  • http://www.springframework.org/schema/websocket
  • http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd ">
  • <!-- @Autowired等注解驱动 -->
  • <context:annotation-config />
  • <mvc:annotation-driven/>
  • <!--一定要扫描指定的项目报-->
  • <context:component-scan base-package="com.soccermaster.websocket"></context:component-scan>
  • <context:component-scan base-package="com.soccermaster.service"></context:component-scan>
  • <context:component-scan base-package="com.soccermaster.dao"></context:component-scan>
  • <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
  • <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView"
  • p:prefix="/WEB-INF/pages/" p:suffix=".jsp">
  • </bean>
  • </beans>

复制代码

二、web.xml配置

注意:必须将相应filter和servlet加入

Java代码

  1. <async-supported>true</async-supported>

复制代码

  1. <?xml version="1.0" encoding="UTF-8"?>
  • <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  • <display-name>spring websocket信息推送</display-name>
  • <welcome-file-list>
  • <welcome-file>testSocket.jsp</welcome-file>
  • </welcome-file-list>
  • <listener>
  • <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  • </listener>
  • <listener>
  • <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  • </listener>
  • <servlet>
  • <servlet-name>SpringMVC</servlet-name>
  • <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  • <init-param>
  • <param-name>contextConfigLocation</param-name>
  • <param-value>classpath:spring-mvc.xml</param-value>
  • </init-param>
  • <load-on-startup>1</load-on-startup>
  • <async-supported>true</async-supported>
  • </servlet>
  • <servlet-mapping>
  • <servlet-name>SpringMVC</servlet-name>
  • <url-pattern>/</url-pattern>
  • </servlet-mapping>
  • <context-param>
  • <param-name>contextConfigLocation</param-name>
  • <param-value>classpath:spring-mybatis.xml</param-value>
  • </context-param>
  • <filter>
  • <filter-name>encodingFilter</filter-name>
  • <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  • <async-supported>true</async-supported>
  • <init-param>
  • <param-name>encoding</param-name>
  • <param-value>UTF-8</param-value>
  • </init-param>
  • </filter>
  • <filter-mapping>
  • <filter-name>encodingFilter</filter-name>
  • <url-pattern>/*</url-pattern>
  • </filter-mapping>
  • <session-config>
  • <session-timeout>30</session-timeout>
  • </session-config>
  • </web-app>

复制代码

三、代码

a、websocketconfig

Java代码

  1. package com.soccermaster.websocket;
  • 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;
  • import org.springframework.context.annotation.Bean;
  • @Configuration
  • @EnableWebMvc
  • @EnableWebSocket
  • public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
  • public WebSocketConfig() {
  • }
  • @Override
  • public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  • registry.addHandler(systemWebSocketHandler(), "/websck").addInterceptors(new WebSocketHandshakeInterceptor());
  • System.out.println("registed!");
  • registry.addHandler(systemWebSocketHandler(), "/sockjs/websck/info").addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS();
  • }
  • @Bean
  • public WebSocketHandler systemWebSocketHandler() {
  • //return new InfoSocketEndPoint();
  • return new SystemWebSocketHandler();
  • }
  • }

复制代码

b、WebSocketHandshakeInterceptor

Java代码

  1. package com.soccermaster.websocket;
  • import java.util.Map;
  • import org.springframework.http.server.ServerHttpRequest;
  • import org.springframework.http.server.ServerHttpResponse;
  • import org.springframework.stereotype.Component;
  • import org.springframework.web.socket.WebSocketHandler;
  • import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
  • @Component
  • public class WebSocketHandshakeInterceptor 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);
  • }
  • }

复制代码

c、SystemWebSocketHandler

Java代码

  1. package com.soccermaster.websocket;
  • import java.io.IOException;
  • import java.util.ArrayList;
  • import org.slf4j.Logger;
  • import org.slf4j.LoggerFactory;
  • import org.springframework.beans.factory.annotation.Autowired;
  • import org.springframework.stereotype.Component;
  • 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.soccermaster.service.IMatchService;
  • import com.soccermaster.util.json.JsonConvert;
  • /**
  • *
  • */
  • @Component
  • public class SystemWebSocketHandler implements WebSocketHandler {
  • @Autowired
  • private IMatchService matchService;
  • private static final Logger logger;
  • private static final ArrayList<WebSocketSession> users;
  • static {
  • users = new ArrayList<WebSocketSession>();
  • logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
  • }
  • @Override
  • public void afterConnectionEstablished(WebSocketSession session)
  • throws Exception {
  • logger.debug("connect to the websocket success......");
  • System.out.println("connect to the websocket success......");
  • session.sendMessage(new TextMessage("Server:connected OK!"));
  • users.add(session);
  • }
  • @Override
  • public void handleMessage(WebSocketSession wss, WebSocketMessage<?

    > wsm)

  • throws Exception {
  • logger.debug("websocket handle message......");
  • TextMessage returnMessage = new TextMessage(result);
  • wss.sendMessage("服务端返回信息");
  • //sendMessageToUsers(wss, wsm);
  • }
  • @Override
  • public void handleTransportError(WebSocketSession wss, Throwable thrwbl)
  • throws Exception {
  • if (wss.isOpen()) {
  • wss.close();
  • }
  • users.remove(wss);
  • logger.debug("websocket connection closed happen error......");
  • System.out.println("websocket connection closed happen error......");
  • }
  • @Override
  • public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs)
  • throws Exception {
  • System.out.println("websocket connection closed......");
  • users.remove(wss);
  • logger.debug("websocket connection closed......");
  • }
  • @Override
  • public boolean supportsPartialMessages() {
  • return false;
  • }
  • }

复制代码

四、相关项目jar包

http://pan.baidu.com/s/1sjI9GOt

如上基本完毕 spring websocket

环境要求tomcat7及其以上  + jdk 1.7

【spring+websocket的使用】的更多相关文章

  1. spring websocket源码分析续Handler的使用

    1. handler的定义 spring websocket支持的消息有以下几种: 对消息的处理就使用了Handler模式,抽象handler类AbstractWebSocketHandler.jav ...

  2. spring WebSocket详解

    场景 websocket是Html5新增加特性之一,目的是浏览器与服务端建立全双工的通信方式,解决http请求-响应带来过多的资源消耗,同时对特殊场景应用提供了全新的实现方式,比如聊天.股票交易.游戏 ...

  3. spring+websocket整合

    java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序: Apach Tomcat 8.0.3+MyEclipse+maven+JD ...

  4. 【转】Spring websocket 使用

    http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html https://spr ...

  5. web即时通讯2--基于Spring websocket达到web聊天室

    如本文所用,Spring4和websocket要构建web聊天室,根据框架SpringMVC+Spring+Hibernate的Maven项目,后台使用spring websocket进行消息转发和聊 ...

  6. spring+websocket综合(springMVC+spring+MyBatis这是SSM框架和websocket集成技术)

    java-websocket该建筑是easy.儿童无用的框架可以在这里下载主线和个人教学好java-websocket计划: Apach Tomcat 8.0.3+MyEclipse+maven+JD ...

  7. Spring 学习——基于Spring WebSocket 和STOMP实现简单的聊天功能

    本篇主要讲解如何使用Spring websocket 和STOMP搭建一个简单的聊天功能项目,里面使用到的技术,如websocket和STOMP等会简单介绍,不会太深,如果对相关介绍不是很了解的,请自 ...

  8. Spring Websocket实现简易在线聊天功能

    针对Spring Websocket的实现,我参照了其他博主的文章https://www.cnblogs.com/leechenxiang/p/5306372.html 下面直接给出实现: 一.引入相 ...

  9. Spring WebSocket踩坑指南

    Spring WebSocket踩坑指南 本次公司项目中需要在后台与安卓App间建立一个长连接,这里采用了Spring的WebSocket,协议为Stomp. 关于Stomp协议这里就不多介绍了,网上 ...

  10. Spring WebSocket初探2 (Spring WebSocket入门教程)<转>

    See more: Spring WebSocket reference整个例子属于WiseMenuFrameWork的一部分,可以将整个项目Clone下来,如果朋友们有需求,我可以整理一个独立的de ...

随机推荐

  1. 数据结构——RMQ

    RMQ 今天临放学前终于是学会了RMQ,特此写一篇题解来缅怀 RMQ是一种数据结构,用途是查询区间内最大值或最小值 或者你所要求的任意条件,主要思想是二进制的思想,其中还用到了dp的思想, 是一种非常 ...

  2. C#中byte类型运算

    首先看下面一段代码 byte x = 1; byte y = 2; byte z = x + y; Console.WriteLine(z); 可能很多人会说显示结果是3. 其实,这段代码无法运行,因 ...

  3. viewport移动端适配,读文笔记

    文章地址: viewport移动端适配 笔记: 移动端适配目的: 希望在屏幕尺寸大小不同的手机上进行访问页面时,页面显示的效果能合理的展示,我们期望的是在手机屏幕较大时显示的内容比较大一些,手机屏幕小 ...

  4. 关闭 macOS Google Chrome 黑暗模式风格

    终端执行命令 defaults write com.google.Chrome NSRequiresAquaSystemAppearance -bool YES 恢复 defaults write c ...

  5. 第二讲:vcs debugging basics

    要求: 1.describe three methods of debugging verilog code using vcs 2.invoke ucli debugger(不重要) 3.debug ...

  6. LeetCode(26) Remove Duplicates from Sorted Array

    题目 Given a sorted array, remove the duplicates in place such that each element appear only once and ...

  7. JavaScript中离线应用和客户端存储(cookies、sessionStorage、localStorage)

    一.离线应用 所谓离线web应用,就是在设备不能上网的情况下仍然可以运行的应用. 开发离线web应用需要几个步骤:首先,确保应用知道设备是否能上网,以便下一步执行正确的操作:然后,应用还必须能访问一定 ...

  8. python协程有多厉害?

    爬一个××网站上的东西,测算了一下协程的速度提升到底有多大,网站链接就不放了... import requests from bs4 import BeautifulSoup as sb import ...

  9. Light oj-1259 - Goldbach`s Conjecture

                                                                                    1259 - Goldbach`s Co ...

  10. 【bzoj1090】 [SCOI2003]字符串折叠

    [bzoj1090] [SCOI2003]字符串折叠 2014年3月9日3,1140 Description 折叠的定义如下: 1. 一个字符串可以看成它自身的折叠.记作S  S 2. X(S)是X ...