[websocket] websocket 생성하기

첸첸·2021년 11월 11일
0

webSocket in java

목록 보기
2/9

websocket 생성방법


The JAVA EE 는 웹소켓을 위한 Java API를 제공하고 있다.

Java API가 가지고 있는 패키지
1. javax.websocket.server
	- server endpoints를 위한 패키지	
   	- server endpoints를 생성하고 구성하기 위한 annotations,classes, interface 제공
2. javax.websocket
	- client endpoints와 server endpoints를 위한 패키지
	- client와 server endpoints를 위한 공통적인 annotations,classes, interface, exception 제공
    

Java API는 WebSocket 두 종류의 endpoint를 만드는 방법을 제공하고 있다.

1. programmatic endpoints
2. annotated endpoints

✔ 기본 방법

1. endpoint 클래스 생성
2. endpoint의 lifecycle 메소드 구현
3. endpoint에 비즈니스 로직 구현
4. 웹 어플리케이션에 endpoint deploy

Progrmaatic endpoints


public class EchoEndpoint extends Endpoint {
   @Override
   public void onOpen(final Session session, EndpointConfig config) {
      session.addMessageHandler(new MessageHandler.Whole<String>() {
         @Override
         public void onMessage(String msg) {
            try {
               session.getBasicRemote().sendText(msg);
            } catch (IOException e) { ... }
         }
      });
   }
}
//Session 파라미터는 이 endpoint와 원격 endpoint 사이의 대화를 나타냄
//addMessageHandler 메소드는 message handlers를 등록하고, getBasicRemote 메서드는 원격 endpoint를 나타내는 객체 리턴
//onMessage 메서드는 endpoint가 text 메세지를 받을 때 호출됨
  • Endpoint 클래스는 세가지의 lifecycle 메소드를 가진다
    1.onOpen
    2.onClose
    3.onError

programmatic endpoint를 배포하기 위해서는, java어플리케이션에 다음 코드를 사용하면 된다.

ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/echo").build();

배포한 후에는 endpoint는 아래로 접근 가능

ws://<host>:<port>/<application>/echo;
//예시
ws://localhost:8080/echoapp/echo

Annotated endpoints


동일한 programmatic endpoint 보다 간결하며, @ServerEndpoint에 정의 된 상대 경로에 자동으로 배포된다. message handler를 위한 추가적인 클래스를 만들 필요 없음.

@ServerEndpoint("/echo")
public class EchoEndpoint {
   @OnMessage
   public void onMessage(Session session, String msg) {
      try {
         session.getBasicRemote().sendText(msg);
      } catch (IOException e) { ... }
   }
}

websocket Endpoint Lifecycle Annotation

AnnotationEvent
OnOpenConnection opened
OnMessageMessage received
OnErrorConnection error
OnCloseConnection closed

참고
https://docs.oracle.com/javaee/7/tutorial/websocket005.html

0개의 댓글