当前位置:首页 > 开发 > 编程语言 > Spring > 正文

spring+websocket的使用

发表于: 2015-06-10   作者:dalan_123   来源:转载   浏览:
摘要: 一、spring配置文件 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.or

一、spring配置文件

<?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添加

<async-supported>true</async-supported>

 

<?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

 

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

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

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

 五、补充 关于浏览器不支持websocket , 通过http请求来模拟注意事宜

 需要添加jackson2相关的jar包(见附件)

 

 

spring+websocket的使用

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
实现每天15点给所有在线用户推送一个广告或是推送一个通知之类的, 相关环境 Nginx,Spring4.1.6当前
最近因工作的需要,需要检查html那些不合理或则什么没有闭合。在网上找了很久都没有找到比较合适的
timepicker是datepicker的一个插件,需要单独下载,可datepicker配合使用的话,可以实现用户精确到
1. 首先到 https://github.com/这里创建一个帐号。   2. 创建Repository,到个人首页以后,点击 N
1 注册组件。 其实一个filter就是一个COM组件,所以使用之前需要注册,可以有两种方法对组件进行注
pwd 显示当前目录 passwd 修改密码 1.注销 exit CTRL+D 2.重启 reboot shut down –r now init 6 3.
1、DBUtils下载:http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi 2、API
Dapper是一个轻型的ORM类。代码就一个SqlMapper.cs文件,主要是IDbConnection的扩展方法,编译后就40
CDH使用文档 前言:CDH在安装完毕之后,通过CM给集群添加服务组件,就可以开始各个组件的使用了,本
‍‍我觉得我需要先介绍一下 zookeeper的基础算法 Paoxs算法 Paoxs算法是Lamport在98年提出的 之后
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号