U E D R , A S I H C RSS

html5/websocket (rev. 1.4)

html5/websocket

개요

사용법

지원 여부 확인

// 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>
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:41
Processing time 0.0377 sec