Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Html5/websocket

From ZeroWiki
Revision as of 14:01, 26 March 2026 by Maintenance script (talk | contribs) (Repair MoniWiki formatting after migration)

[[pagelist(html5)]]

개요

  • 최근의 웹 앱은 이벤트 드리븐 방식을 요구한다.
    • 실시간성, 양방향성
    • http의 한계 : 반이중 통신, http head 오버헤드, polling 방식
  • websocket
    • 전이중 통신, binary 통신 가능
  • port : 80/443
ws://

, secure websocket : {{{wss://}}}

  • handshake, cookie-based authentication
  • ajax vs websocket
    • websocket이 50배 빠르다

사용법

지원 여부 확인

// test if the browser supports web sockets
if ("WebSocket" in window) {
        debug("Browser supports web sockets!", 'success');
        connect($('#host').val());
        $('#console_send').removeAttr('disabled');
} else {
            debug("Browser does not support web sockets", 'error');
};

이벤트

연결

  • 기본 포트 http, https와 동일한 80,443을 이용한다
var wSocket = new WebSocket("ws://yourdomain/demo");

데이터 송신

  • WebSocket 객체의 send 함수로 데이터를 서버로 송신할 수 있다
wSocket.send("송신 메시지");

데이터 수신

  • message 이벤트를 구현
wSocket.onmessage = function(e){ //매개변수 e를 통해 수신된 데이터를 조회할 수 있다

}

열기/닫기

  • open 이벤트: 연결이 설정되면 발생
  • close 이벤트: 연결이 끊어지면 발생

전체적 형태

<script>
  var wSocket = new WebSocket("ws:yourdomain/demo");
  
  wSocket.onmessage = function(e){  alert(e.data);  }  

  wSocket.onopen = function(e){ alert("서버 연결 완료"); } 
  wSocket.onclose = function(e){ alert("서버 연결 종료"); }  

  function send(){ //서버로 데이터를 전송하는 메서드
    wSocket.send("Hello");
  }
</script>

참고