spring 프레임워크에서 웹소켓 구축

5281 단어 springwebsocket
본고는 Apach Tomcat 8.0.3+MyEclipse+maven+JDK1.7을 바탕으로 합니다.
spring4.0 이후 웹소켓 기술에 대한 지원을 추가했습니다. 현재 프로젝트는 SSM(springMVC+spring+MyBatis) 프레임워크를 사용하고 있기 때문에spring이 가지고 있는 웹소켓을 선택해야 합니다.
1 마븐의pom.xml에 웹소켓에 의존하는jar 패키지 추가

<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-core</artifactId>
 <version>2.4.0</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.4.0</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-websocket</artifactId>//version spring mvc version , 
  <version>4.0.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-messaging</artifactId>
  <version>4.0.5.RELEASE</version>
</dependency>
2 spring-mvc를 업데이트합니다.xml에서namespace.xsd 버전

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:websocket="http://www.springframework.org/schema/websocket"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
처리 클래스와 악수 프로토콜의spring 설정(applicationContext.xml 파일)

<bean id="websocket" class="com.xl.websocket.handler"/>

<websocket:handlers>
  <websocket:mapping path="/websocket" handler="websocket"/>
  <websocket:handshake-interceptors>
  <bean class="com.xl.websocket.HandshakeInterceptor"/>
  </websocket:handshake-interceptors>
   <websocket:sockjs/>
</websocket:handlers>
webconfig

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(new HelloHandler(), "/hello").addInterceptors(new HandshakeInterceptor()).withSockJS().setHttpMessageCacheSize(20000);

    }
3 악수(handshake) 인터페이스 만들기

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
 @Override
 public boolean beforeHandshake(ServerHttpRequest arg0,
  ServerHttpResponse arg1, WebSocketHandler arg2,
  Map<String, Object> arg3) throws Exception {
 
 System.out.println("---- Before Handshake ----");
 return super.beforeHandshake(arg0, arg1, arg2, arg3);
 }
 
 @Override
 public void afterHandshake(ServerHttpRequest request,
  ServerHttpResponse response, WebSocketHandler wsHandler,
  Exception ex) {
 
 System.out.println("---- After Handshake ----");
 super.afterHandshake(request, response, wsHandler, ex);
 }
}
4 웹소켓 처리 클래스 만들기

public class HelloHandler extends TextWebSocketHandler {
 
 public static List<WebSocketSession> users;
 static{
 users = new ArrayList<WebSocketSession>();
 }
 
 @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) {
    // 
    System.out.println("text message: " + session.getId() + "-" + message.getPayload());
  }

  @Override
  public void afterConnectionEstablished(WebSocketSession session)
      throws Exception {
    //  
    System.out.println("afterConnectionEstablished");
    System.out.println("getId:" + session.getId());
    System.out.println("getLocalAddress:" + session.getLocalAddress().toString());
    System.out.println("getTextMessageSizeLimit:" + session.getTextMessageSizeLimit());
    System.out.println("getUri:" + session.getUri().toString());
    System.out.println("getPrincipal:" + session.getPrincipal());
    System.out.println(soslistService.getsss());
    session.sendMessage(new TextMessage(" "));
    
    users.add(session);
  }

  @Override
  public void handleTransportError(WebSocketSession session,
      Throwable exception) throws Exception {
    //  
    System.out.println("handleTransportError");
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session,
      CloseStatus closeStatus) throws Exception {
    //  
    System.out.println("afterConnectionClosed");
  }

  @Override
  public boolean supportsPartialMessages() {
    // TODO Auto-generated method stub
    return false;
  }
}

이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기