WebSocket学习笔记

maven导入jar包:


   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

  
   org.springframework  
   spring-websocket  
   4.0.5.RELEASE  
  
  
   org.springframework  
   spring-messaging  
   4.0.5.RELEASE  
 

Websocket配置文档-WebSocketConfig :

package com.dido.crawler.controller;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import com.dido.crawler.utils.websocket.HandshakeInterceptor;
import com.dido.crawler.utils.websocket.WebSocketHander;

@Configuration  
@EnableWebSocket  
public class WebSocketConfig implements WebSocketConfigurer {  
  
	private static final Logger logger = Logger.getLogger(WebSocketConfig.class);
    @Override  
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {  
    	/**
    	 * 支持websocket 的 connection
    	 */
        registry.addHandler(myhandler(), "/websocket.do").addInterceptors(myInterceptors()).setAllowedOrigins("*");
        /**
         * 不支持websocket的connenction,采用sockjs
         */
        registry.addHandler(myhandler(), "/sockjs/websocket.do").addInterceptors(myInterceptors()).withSockJS();  
    }  
  
    @Bean  
    public WebSocketHandler myhandler() {  
        return new WebSocketHander();  
    }  
  
    @Bean  
    public HandshakeInterceptor myInterceptors() {
        return new HandshakeInterceptor();  
    }  
}  

WebSocket工作类-WebSocketHander :

package com.dido.crawler.utils.websocket;
import org.apache.log4j.Logger;
import org.springframework.web.socket.*;
import java.io.IOException;
import java.util.ArrayList;

public class WebSocketHander implements WebSocketHandler {

    private static final Logger logger = Logger.getLogger(WebSocketHander.class);

    private static final ArrayList users = new ArrayList();

    private String userName="";

    // 初次链接成功执行
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("链接成功......");
        users.add(session);
        session.sendMessage(new TextMessage("hello webSocket!"));
    }

    // 接受消息处理消息
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage webSocketMessage)
            throws Exception {
        //sendMessageToUsers(new TextMessage(webSocketMessage.getPayload() + ""));
        sendMessageToUser(userName, new TextMessage(webSocketMessage.getPayload() + "yours message"));

    }

    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (webSocketSession.isOpen()) {
            webSocketSession.close();
        }
        logger.debug("链接出错,关闭链接......");
        users.remove(webSocketSession);
    }

    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        logger.debug("链接关闭......" + closeStatus.toString());
        users.remove(webSocketSession);
    }

    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();
            }
        }
    }

    /**
     * 给某个用户发送消息,模拟给admin发信息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }
}

拦截器配置-HandshakeInterceptor:

package com.dido.crawler.utils.websocket;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
    // 初次握手访问前
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse,
            WebSocketHandler webSocketHandler, Map map) throws Exception {
        return super.beforeHandshake(request, serverHttpResponse, webSocketHandler, map);
    }

    // 初次握手访问后
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
            WebSocketHandler webSocketHandler, Exception e) {
    	super.afterHandshake(serverHttpRequest, serverHttpResponse, webSocketHandler, e);
    }
}

JavaScript代码:


你可能感兴趣的:(技术积累,websocket)