본문 바로가기

Web

Web Socket 사용법

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


특징

웹소켓은 full-duplex 통신을 지원

 bytes 스트림을 사용하지 않고 오로지 UTF8 포멧의 메시지 스트림만 허용 

▶ 웹소켓은 HTTP를 기반으로 하면서도 HTTP의 문제점을 해결하는 것을 목표




Ajax(Timer) vs WebSocket 비교
 Ajax로 만든 웹 페이지 - 서버 측에서 클라이언트로 보낼 수가 없음, 대응책으로 설정 주기마다 데이터를 데이터 갱신
 웹 소켓 - 서버에서도 클라이언트를 인지를 하는 상태이기에 양방향 통신 가능



브라우저 지원



개인적으로는 특성상 꼭 써야하는거 아니라면 브라우저 제약으로 인하여 타이머 선호








사용법


□ dependency 추가

 

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.0.9.RELEASE</version>

</dependency>

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
</dependency>





□ servlet-context 

 


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

         xmlns:mvc="http://www.springframework.org/schema/mvc

         xmlns:context="http://www.springframework.org/schema/context"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance

         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:p="http://www.springframework.org/schema/p"
        xmlns:websocket="http://www.springframework.org/schema/websocket"
         xmlns:util="http://www.springframework.org/schema/util

         xmlns:task="http://www.springframework.org/schema/task"
         xsi:schemaLocation="http://www.springframework.org/schema/aop 

                                 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                                http://www.springframework.org/schema/mvc 

                                 http://www.springframework.org/schema/mvc/spring-mvc.xsd
                                http://www.springframework.org/schema/beans 

                                 http://www.springframework.org/schema/beans/spring-beans.xsd        
                                http://www.springframework.org/schema/task 

                                 http://www.springframework.org/schema/task/spring-task-3.0.xsd
                                http://www.springframework.org/schema/util 

                                 http://www.springframework.org/schema/util/spring-util-3.1.xsd
                                http://www.springframework.org/schema/websocket 

                                 http://www.springframework.org/schema/websocket/spring-websocket.xsd
                                http://www.springframework.org/schema/context 

                                 http://www.springframework.org/schema/context/spring-context.xsd">

(추가)

<websocket:handlers>
        <websocket:mapping handler="RefreshHandler" path="/permit/RefreshSocket.do" />
</websocket:handlers>
<bean id="RefreshHandler" class="com.chience.odin.socket.RefreshSocket" />






□ RefreshSocket Class

 

public class RefreshSocket extends TextWebSocketHandler implements InitializingBean {

    Set<WebSocketSession> Resource_Sesstion= new HashSet<WebSocketSession>();

    public RefreshSocket() {
        super();
    }
    @Override // DisConnect
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status){
        try {
            super.afterConnectionClosed(session, status);
            System.out.println("remove Session");
            StaticSocket.getResource_Sesstion().remove(session);
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
    @Override // Connect
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        System.out.println("new Session");
        StaticSocket.getResource_Sesstion().add(session);
    }
    @Override // receive message
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    }
    @Override
    public boolean supportsPartialMessages() {
        return super.supportsPartialMessages();
    }
    public void sendMessage(String message) {
        
    }
    @Override
    public void afterPropertiesSet() throws Exception {
    }
}





□ JAVASCRIPT

 

<script type="text/javascript">
     var wsUri = "ws://192.168.0.190:8080/odin/permit/RefreshSocket.do";
     websocket = new WebSocket(wsUri);
     websocket.onopen = function(evt) {
             onOpen(evt)
         };
         websocket.onmessage = function(evt) {
             onMessage(evt)
         };
         websocket.onerror = function(evt) {
             onError(evt)
         };
     function onOpen(evt) {
        console.log("open");
     }
     function onMessage(evt) {
     }
     function onError(evt) {
         console.log("error");
     }
     function doSend(message) {

     }
     function writeToScreen(message) {

     }
</script>









'Web' 카테고리의 다른 글

rabbitmq - web  (0) 2018.02.09
tomcat + apache 연동 (mok_jk)  (0) 2017.11.08
centos7 + tomcat8 자동실행  (0) 2017.11.08
Spring Security  (0) 2017.06.12
엑셀(JXL) 다운로드  (0) 2017.04.27