websocket-spring 整合

环境:jdk1.7.0_79  tomcat 7.0.69  spring 4.1.4

sockjs下载地址:https://github.com/sockjs/sockjs-client/blob/master/dist/sockjs-0.3.4.js

package com.websocket;

/**
 * websocket 常量
 * @author caihao
 *
 */
public class Constants {

    //http session 中 用户名的key值
    public static String SESSION_USERNAME = "session_username";
    //websocket session 中 用户名的key值
    public static String WEBSOCKET_USERNAME = "websocket_username";
}
package com.websocket;

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 WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{

    public void registerWebSocketHandlers(WebSocketHandlerRegistry reg) {
        String websocket_url = "/webSocketServer";                     //设置websocket的地址
        reg.addHandler(systemWebSocketHandler(), websocket_url)        //注册到Handler
           .addInterceptors(new WebSocketHandshakeInterceptor())    //注册到Interceptor
           ;

        String sockjs_url    = "/sockjs/webSocketServer";           //设置sockjs的地址
        reg.addHandler(systemWebSocketHandler(),sockjs_url )        //注册到Handler
           .addInterceptors(new WebSocketHandshakeInterceptor())    //注册到Interceptor
           .withSockJS();                                           //支持sockjs协议 

    }

    @Bean
    public WebSocketHandler systemWebSocketHandler(){
        return new SystemWebSocketHandler();
    }

}
package com.websocket;

import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 *
 * @author caihao
 *
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    //握手前
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler handler,
            Map<String, Object> attr) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
                attr.put(Constants.WEBSOCKET_USERNAME,userName);
            }
        }
        return true;
    }

    //握手后
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
            WebSocketHandler handler, Exception e) {
    }
}
package com.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 *
 * @author caihao
 *
 */
public class SystemWebSocketHandler implements WebSocketHandler {

    private static final List<WebSocketSession> users = new ArrayList<WebSocketSession>();

    @Autowired
    private WebSocketService webSocketService;

    //连接已建立
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        users.add(session);
    }

    //消息接收处理
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> ws_msg)
            throws Exception {
        //消息处理
    }

    //连接已关闭
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
            throws Exception {
        users.remove(session);
    }

    //异常处理
    public void handleTransportError(WebSocketSession session, Throwable e)
            throws Exception {
        if(session.isOpen()) session.close();
        users.remove(session);
    }

    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 自定义接口
     * 给所有在线用户发送消息
     * @param message
     * @throws IOException
     */
    public void sendMessageToUsers(TextMessage message) throws IOException {
        for (WebSocketSession user : users) {
            if (user.isOpen()) user.sendMessage(message);
        }
    }

    /**
     * 自定义接口
     * 给某个用户发送消息
     * @param userName
     * @param message
     * @throws IOException
     */
    public void sendMessageToUser(String userName, TextMessage message) throws IOException {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
               if (user.isOpen()) {
                   user.sendMessage(message);
                   break;
               }
            }
        }
    }

}
<?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"
        xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <context:annotation-config />
</beans>
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.*"/>
</beans>
<?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"
    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">
    <!-- 加载Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value> classpath:spring.xml </param-value>
    </context-param>
    <!-- Spring MVC -->
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
<properties>
        <spring.version>4.1.4.RELEASE</spring.version>
  </properties>

  <dependencies>
    <!-- springframework lib -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- end springframework lib -->

        <!-- WEB SOCKET API -->
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>
        <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>
        <!-- WEB SOCKET API -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>

</head>
<body>
<div id="msgcount"></div>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
<script type="text/javascript" src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>

 <script>
            var websocket;
            if (‘WebSocket‘ in window) {
                websocket = new WebSocket("ws://localhost:8080/websocket3/webSocketServer?userid=123");
            } else if (‘MozWebSocket‘ in window) {
                websocket = new MozWebSocket("ws://localhost:8080/websocket3/webSocketServer");
            } else {
                websocket = new SockJS("http://localhost:8080/websocket3/sockjs/webSocketServer");
            }
            websocket.onopen = function (evnt) {
                console.log(‘ws clint:open websocket‘)
                 //发送消息
                 var msg = ‘userid=1‘;
                console.log(‘ws clint:send msg:‘+msg)
                    websocket.send(msg);
            };
            websocket.onmessage = function (evnt) {
                console.log(‘ws client:get message ‘)
                $("#msgcount").html("(<font color=‘red‘>"+evnt.data+"</font>)")
            };
            websocket.onerror = function (evnt) {
                console.log(‘ws client:error ‘+evnt)
            };
            websocket.onclose = function (evnt) {
                console.log(‘ws clent:close ‘)
            }

</script>
</body>
</html>
时间: 2024-08-27 17:41:09

websocket-spring 整合的相关文章

springMVC+MyBatis+Spring 整合(3)

spring mvc 与mybatis 的整合. 加入配置文件: spring-mybaits.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" xm

Spring整合Struts2

Spring整合Struts21整合目的:让Spring的IOC容器去管理Struts2的Action, 2Struts2是web开源框架,Spring要整合Struts2,也就是说要在web应用使用Spring①. 需要额外加入的 jar 包:spring-web-4.0.0.RELEASE.jarspring-webmvc-4.0.0.RELEASE.jar ②. Spring 的配置文件, 和非 WEB 环境没有什么不同 ③. 需要在 web.xml 文件中加入如下配置: <!-- 配置

Spring整合hibernate4:事务管理

Spring和Hibernate整合后,通过Hibernate API进行数据库操作时发现每次都要opensession,close,beginTransaction,commit,这些都是重复的工作,我们可以把事务管理部分交给spring框架完成. 配置事务(xml方式) 使用spring管理事务后在dao中不再需要调用beginTransaction和commit,也不需要调用session.close(),使用API  sessionFactory.getCurrentSession()来

springMVC+MyBatis+Spring 整合(4) ---解决Spring MVC 对AOP不起作用的问题

解决Spring MVC 对AOP不起作用的问题 分类: SpringMVC3x+Spring3x+MyBatis3x myibaits spring J2EE2013-11-21 11:22 640人阅读 评论(1) 收藏 举报 用的是 SSM3的框架 Spring MVC 3.1 + Spring 3.1 + Mybatis3.1第一种情况:Spring MVC 和 Spring 整合的时候,SpringMVC的springmvc.xml文件中 配置扫描包,不要包含 service的注解,S

Spring整合MyBatis

首先下载jar包  mybatis-spring.jar 原因spring3.0出来的早,MyBatis3.0晚,意味着Spring不愿意去在一个没有做出发布版本的MyBatis上做过多的设置.所以,最终jar包提供者第三方. <!--Mybatis+Spring整合--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId&g

JMS 之 Active MQ 的spring整合

一.与spring整合实现ptp的同步接收消息 pom.xml: <!-- https://mvnrepository.com/artifact/org.springframework/spring-jms --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>4.3.7.RE

8 -- 深入使用Spring -- 7...2 MVC框架与Spring整合的思考

8.7.2 MVC 框架与Spring整合的思考 对于一个基于B/S架构的JAVA EE 应用而言,用户请求总是向MVC框架的控制器请求,而当控制器拦截到用户请求后,必须调用业务逻辑组件来处理用户请求.此时有一个问题:控制器应该如何获得业务逻辑组件? 最容易想到的策略是,直接通过new 关键字创建业务逻辑组件,然后调用业务逻辑组件的方法,根据业务逻辑方法的返回值确定结果. 在实际的应用中,很少见到采用上面的访问策略,因为这是一种非常差的策略.不这样做至少有如下三个原因: ⊙ 控制器直接创建业务逻

Spring整合strus2简单应用总结

本身strus2没接触过,所以这块学的一知半解,正常不整合的还没学(接着学) step: 1.创建web工程 2.在/WEB-INF/lib引入jar包 asm-3.3.jarasm-commons-3.3.jarasm-tree-3.3.jarcom.springsource.net.sf.cglib-2.2.0.jarcom.springsource.org.aopalliance-1.0.0.jarcom.springsource.org.aspectj.weaver-1.6.8.RELE

Spring整合jdbc

首先web.xml文件跟往常一样,加载spring容器和加载org.springframework.web.context.ContextLoaderListener读取applicationContext.xml文件初进行始化. 使用spring整合jdbc工具步骤: 1.使用连接池com.mchange.v2.c3p0.ComboPooledDataSource等工具创建数据源. 2.把数据源交给LazyConnectionDataSourceProxy进行管理 3.把LazyConnect

MyBatis Spring整合配置映射接口类与映射xml文件

Spring整合MyBatis使用到了mybatis-spring,在配置mybatis映射文件的时候,一般会使用MapperScannerConfigurer,MapperScannerConfigurer会自动扫描basePackage指定的包,找到映射接口类和映射XML文件,并进行注入.配置如下: [html] view plain copy <!-- 数据源 --> <bean id="dataSource" class="com.mchange.v