首页 > 代码库 > websocket-spring 整合

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>

 

websocket-spring 整合