[자바스크립트][비동기통신] WebSocket

류명운

·

2016. 8. 11. 00:16

반응형

[자바스크립트][비동기통신] WebSocket의 간단한 실습에 대한 포스팅입니다.


1. 지원

  • IE10이상, Chrome, Firefox, Safari, Opera 브라우저를 지원한다.
  • * 아래 그림 참고.


2. 이벤트 및 메소드

2. 1 이벤트

  • open / Socekt.onopen / 소켓 연결이 설정되면 이벤트 발생
  • message / Socket.onmessage / 클라이언트가 서버로부터 데이터를 수신 할 때 이벤트 발생
  • error / Socket.onerror / 통신 오류가 있을 때 이벤트 발생
  • close / Socket.onclose / 접속이 패쇄 될 때 이벤트 발생


2. 2 메소드

  • Socket.send() - 클라이언트에서 서버로 데이터를 송신하는 방법
  • Socket.close() - 기존 연결을 종료하는 방법


3. 클라이언트 예제코드(HTML&Javascript)

      

      


4. 서버 예제코드(Java)

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
  
@ServerEndpoint("/websocket")
public class websocket {
    /***
     * 웹 소켓이 연결되면 호출되는 이벤트
     */
    @OnOpen
    public void handleOpen(){
        System.out.println("client is now connected...");
    }

    /**
     * 웹 소켓으로부터 메시지가 오면 호출되는 이벤트
     * @param message
     * @return
     */
    @OnMessage
    public String handleMessage(String message){
        System.out.println("receive from client : "+message);
        String replymessage = "echo "+message;
        System.out.println("send to client : "+replymessage);
        return replymessage;
    }

    /**
     * 웹 소켓이 닫히면 호출되는 이벤트
     */
    @OnClose
    public void handleClose(){
        System.out.println("client is now disconnected...");
    }

    /**
     * 웹 소켓이 에러가 나면 호출되는 이벤트
     * @param t
     */
    @OnError
    public void handleError(Throwable t){
        t.printStackTrace();
    }
}


반응형