基于springMvc整合websocket

eclipse下,项目结构图:
基于springMvc整合websocket_第1张图片

SocketController类:

package com.iflytek.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.socket.TextMessage;

import com.iflytek.socket.SocketHandler;

/**
 * @desp Socket控制器
 *
 */
@Controller
@RequestMapping(value="/main")
public class SocketController{
	
	private static final Logger logger = LoggerFactory.getLogger(SocketController.class);
	
	@Autowired
	private SocketHandler socketHandler;
	
	@RequestMapping(value="/login")
	public String login(HttpSession session){
		logger.info("用户登录了建立连接啦");
		
		session.setAttribute("user", "yy");
		
		return "home";
	}

	@RequestMapping(value = "/message", method = RequestMethod.GET)
	public String sendMessage(){
		
		socketHandler.sendMessageToUser("yy", new TextMessage("这是一条测试的消息"));
		
		return "message";
	}
	
}

SocketHandler类:

package com.iflytek.socket;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
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;

/**
 * @desp Socket处理类
 *
 */
@Service
public class SocketHandler implements WebSocketHandler{

	private static final Logger logger;
	private static final ArrayList users;
	
	static{
		users = new ArrayList();
		logger = LoggerFactory.getLogger(SocketHandler.class);
	}
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		logger.info("成功建立socket连接");
		users.add(session);
		String username = session.getAttributes().get("user").toString();
		if(username != null){
			session.sendMessage(new TextMessage("我们已经成功建立socket通信了"));
		}
	}

	@Override
	public void handleMessage(WebSocketSession arg0, WebSocketMessage arg1)
			throws Exception {
		
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable error)
			throws Exception {
		if(session.isOpen()){
			session.close();
		}
		logger.error("连接出现错误:"+error.toString());
		users.remove(session);
	}
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1)
			throws Exception {
		logger.debug("连接已关闭");
		users.remove(session);
	}

	@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();
            }
        }
    }
 
    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get("user").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //break;
            }
        }
    }

}

WebSocketConfig类:

package com.iflytek.socket;

import org.springframework.beans.factory.annotation.Autowired;
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.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * @Configuration @Component  
 * 只有一个实例对象,哪怕手动创建也只有一个; 系统会创建对象,如果手动创建,这两个不同
 * 
 * @EnableWebMvc 需要以编程的方式指定视图文件相关配置
 * 
 * @EnableWebSocket 
 *
 */
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
	
	@Autowired
	private SocketHandler socketHandler;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		//注册处理拦截器,拦截url为socketServer的请求
		registry.addHandler(socketHandler, "/socketServer").addInterceptors(new WebSocketInterceptor());
		
		//注册SockJs的处理拦截器,拦截url为/sockjs/socketServer的请求
		registry.addHandler(socketHandler, "/sockjs/socketServer").addInterceptors(new WebSocketInterceptor()).withSockJS();
	}

}

WebSocketInterceptor类:

package com.iflytek.socket;

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;

/**
 * @desp websocket拦截器
 * 
 * HandshakeInterceptor
 * WebSocket握手请求的拦截器. 检查握手请求和响应, 对WebSocketHandler传递属性
 */
public class WebSocketInterceptor implements HandshakeInterceptor{

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
			WebSocketHandler handler, Exception exception) {
		
	}
	
	/**
	 * @desp 将HttpSession中对象放入WebSocketSession中
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler handler,
			Map map) throws Exception {
		if(request instanceof ServerHttpRequest){
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession();
			if(session != null){
				//区分socket连接以定向发送消息
				map.put("user", session.getAttribute("user"));
			}
		}
		return true;
	}

}

servlet-context.xml:




	
	
	
	

	
	
	
	
	
	
	
	

	
	
		
		
	
	
	
	
	
	


application-config.xml:



		
	
	
	

log4j.xml:





	
	
		
		
			
		
	
	
	
	
		
	
	
	
	
		
	
	
	
		
	
	
	
		
	

	
		
	

	
	
		
		
	
	


home.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String wsPath = "ws://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


	Home


Hello world! This is a WebSocket demo!

message.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




message


	

已经发送消息了

web.xml:


 

  Archetype Created Web Application
  
  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    true
    
      encoding
      UTF-8
    
    
      forceEncoding
      true
    
  
  
    characterEncodingFilter
    /*
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    contextConfigLocation
    classpath:spring/application-config.xml
  
  
    appServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring/appServlet/servlet-context.xml
    
    1
    true
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
    appServlet
    /
  
  


pom.xml:


    4.0.0
    com.ifly
    websocket
    war
    0.0.1-SNAPSHOT
    websocket Maven Webapp
    http://maven.apache.org
  
    
    
        
            aliyun
            aliyun
            http://maven.aliyun.com/nexus/content/groups/public
        
     
    
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.7
                    1.7
                
            
        
	    websocket
    
    
    
        UTF-8
        UTF-8
        4.1.2.RELEASE
        1.6.6
    
  
	
	    
	        javax.servlet
	        servlet-api
	        2.5
	        provided
	    
	    
	        javax.servlet.jsp
	        jsp-api
	        2.1
	        provided
	    
	    
	        org.springframework
	        spring-context
	        ${org.springframework.version}
	    
	    
	        org.springframework
	        spring-webmvc
	        ${org.springframework.version}
	    
	    
	    
          
           org.springframework  
           spring-websocket  
           ${org.springframework.version}  
          
        
        
            org.slf4j
            slf4j-api
            ${org.slf4j.version}
        
    
    


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