利用spring-websocket包搭建websocket服务

折腾了将近一天,终于搭建好websocket服务,中间遇到不少的坑,现在记录一下,也供他们参考少走弯路。

开发环境:4.2.5.RELEASE     Tomcat8   jdk8  maven

spring搭建websocket有两种方式:

1、利用javaee-api以注解的形式搭建,见上一篇博文《spring+tomcat8实现websocket


2、利用spring-websocket包搭建,本篇介绍的内容。

注意:这种方式必须注释掉这个,不然会冲突


需要用到的spring包:

 
           org.springframework  
           spring-websocket  
           ${spring.version}  
        
 
          
           org.springframework  
           spring-messaging  
           ${spring.version}  
        

其他辅助包:


            com.fasterxml.jackson.core
            jackson-core
            ${jackson-version}
        

        
            com.fasterxml.jackson.core
            jackson-databind
            ${jackson-version}
        

        
            com.fasterxml.jackson.core
            jackson-annotations
            ${jackson-version}
        


Java代码:两个类  WebSocketConfig 和 SystemWebSocketHandler


@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(systemWebSocketHandler(),"/webSocketServer");
		registry.addHandler(systemWebSocketHandler(),"/webSocketServer/sockjs").setAllowedOrigins("*").withSockJS();
		 //registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor());
		 //registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS();
		 //registry.addHandler(systemWebSocketHandler(), "/webSocketServer/sockjs").withSockJS();
		 /*registry.addHandler(systemWebSocketHandler(),"/ws").addInterceptors(new WebSocketHandshakeInterceptor());
	        registry.addHandler(systemWebSocketHandler(), "/ws/sockjs").addInterceptors(new WebSocketHandshakeInterceptor())
	                .withSockJS();*/
	}
	
	@Bean
    public WebSocketHandler systemWebSocketHandler(){
        return new SystemWebSocketHandler();
    }
	

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
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.mspj.frame.core.web.controller.BaseWebControllerImpl;

public class SystemWebSocketHandler implements WebSocketHandler {
	 
	private Logger log = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	
    private static final ArrayList users = new ArrayList();;
 
 
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    	System.out.println("ConnectionEstablished");
    	log.debug("ConnectionEstablished");
        users.add(session);
        
        session.sendMessage(new TextMessage("connect"));
        session.sendMessage(new TextMessage("new_msg"));
        
    }
 
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
    	System.out.println("handleMessage" + message.toString());
    	log.debug("handleMessage" + message.toString());
        //sendMessageToUsers();
    	session.sendMessage(new TextMessage(new Date() + ""));
    }
 
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        users.remove(session);
        
        log.debug("handleTransportError" + exception.getMessage());
    }
 
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        users.remove(session);
        log.debug("afterConnectionClosed" + closeStatus.getReason());
        
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
 
    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
}

前端调式页面代码





WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)
    

    

    




echoendpoint test echoendpoint test


最后说下几个坑点:

1、html页面访问限制的问题的:403 Forbidden

registry.addHandler(systemWebSocketHandler(),"/webSocketServer/sockjs").setAllowedOrigins("*").withSockJS();
2、web.xml配置需要升级成3.1

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

3、web.xml里面所有过滤器需要加上

true

如:


        SpringMVC
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring-mvc.xml
        

        1
        true
    

你可能感兴趣的:(Java,websocket,Spring)