SSM WebSocket项目搭建

SpringMvc+Spring+Mybatis +Websocket

关于开发环境 我使用的是IDEA15.0.6 JDK1.7 

首先关于项目搭建 我们需要使用配置好Maven项目Pom.xml引入Jar包



  javax.servlet
  javax.servlet-api
  3.1.0


  org.springframework
  spring-messaging
  4.0.5.RELEASE


  org.springframework
  spring-websocket
  4.0.5.RELEASE


  com.fasterxml.jackson.core
  jackson-annotations
  2.3.0


  com.fasterxml.jackson.core
  jackson-core
  2.3.1


  com.fasterxml.jackson.core
  jackson-databind
  2.3.3


接着我们需要在Spring的applicationContext.xml配置包扫描

<context:component-scan base-package="com.**" annotation-config="true"/>

之后我们需要建立一个类WebSocketConfig接口进行配置Websocket

@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(systemWebSocketHandler(),"webSocket.do").addInterceptors(new SpringWebSocketHandlerInterceptor());

    }
    @Bean
    public WebSocketHandler systemWebSocketHandler(){
        return new SystemWebSocketHandler();
    }
    @Bean
    public WebSocketContainerFactoryBean createWebSocketContainer() {
        WebSocketContainerFactoryBean container = new WebSocketContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(8192);
        return container;
    }

}

@Configuration注解该类,等价于XML中配置beans标签,@Bean相当于spring xml里面的bean标签,@EnableWebSocket这个注解用于springmvc对websocket的支持。

然后我们需要创建WebSocketHandleInterceptor握手拦截器类进行拦截


public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map, Object> attributes) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Before Handshake");
        //获取当前Session
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                //使用userName区分WebSocketHandler,以便定向发送消息
                User currentUser=(User)session.getAttribute(Const.CURRENT_USER);
                System.out.println(currentUser.getId());
                String userName = currentUser.getUsername();
                int userId=currentUser.getId();
                System.out.println(userName);
                if (userName == null) {
                    userName = "default-system";
                }
                attributes.put("WEBSOCKET_USERNAME", userName);
                attributes.put("userId",userId);
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);

    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        // TODO Auto-generated method stub
        super.afterHandshake(request, response, wsHandler, ex);
    }

}

最后我们需要再建立一个SystemWebSocketHandler类处理请求


public class SystemWebSocketHandler implements WebSocketHandler {
    private static ArrayList users = new ArrayList();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.print("连接成功");
        users.add(session);
        System.out.println("当前用户数量: " + users.size());
        String username= (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        int userId=(Integer)session.getAttributes().get("userId");
        System.out.println("用户名 "+username);
        System.out.println("用户ID "+userId);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
        String schatMessage = (String) message.getPayload();//用户输入
        System.out.println("用户输入" + schatMessage);


    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        users.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.print("关闭连接    ");
        removeUser(session);
        System.out.println("用户数量: " + users.size());
    }
    private void sendMessageToUsers(WebSocketMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void removeUser(WebSocketSession session) {
        users.remove(session);
        users.remove(session.getId());
    }



    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}

配置好后 我们就可以启动Tomcat运行项目了


之后我们可以使用websocket在线测试 http://websocket.yszoo.com/

由于我们在WebSocketConfig接口中配置地址为webSocket.do

所以websocket请求地址应为

ws://本地地址:8080/webSocket.do


关于握手拦截器获取不到Session的问题

请注意session登陆的地址要与websocket连接的地址一致

保证地址栏的请求和websocket的请求地址统一

例如Session的登陆地址为127.0.0.1

websocket的请求地址也应该为127.0.01

否则就获取不到Session


你可能感兴趣的:(技术分类)