spring整合websocket开发(服务器端)

  1. websocket开发基于web 3.0以上, 要求tomcat 8 , java 7 版本以上, 在项目中修改web版本
  2. 导入jar包
        
        
            org.springframework
            spring-websocket
            4.3.3.RELEASE
        
        
        
            org.springframework
            spring-messaging
            4.3.3.RELEASE
        
  1. 配置spring配置文件
    
    
    
    
        
    
        
        
            
        
    
  1. 服务器代码
package chatroom.web.websocket;

import java.util.Map;

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;

/**
 * 处理socket握手
 * @author zhang
 *
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
            Map attributes) throws Exception {
        System.out.println("before handshake");
        return super.beforeHandshake(request, response, handler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex) {
        System.out.println("after handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }

}
package chatroom.web.websocket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 消息处理控制器
 * @author zhang
 *
 */
@Controller("websocket")
@RequestMapping("websocket")
public class WebSocketHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        TextMessage returnMessage = new TextMessage(message.getPayload() + " recieved at server");
        session.sendMessage(returnMessage);
    }
}

你可能感兴趣的:(spring整合websocket开发(服务器端))