본문 바로가기
지속가능티끌/JavaScript

JS . 웹브라우저에서 웹소켓 클라이언트 구현

by i.got.it 2023. 10. 29.

 

 

웹브라우저에서 웹소켓 클라이언트 구현 

 

- 웹브라우저 에서  WebSocket API 가 제공되고 있으며 자바스크립트로 이를 활용하여 웹소켓 클라이언트 구현가능. 

 

The WebSocket API (WebSockets) - Web APIs | MDN

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without havi

developer.mozilla.org

 

 

자바스크립트 코드 

- 가장 먼저 new WebSocket 의 인자로 웹소켓 서버 주소 기록하면 해당 서버로 접속 시도하고

- 이후 웹소켓 오픈된 경우 open 이벤트 발생하며 open 이벤트 핸들러 실행된다.

- 서버에서 메시지 송신한 것이 있는 경우 message 이벤트 발생하고 메시시 수신 이벤트 핸들러에서 수신된 데이터 활용한다. 

- open 된 웹소켓이  close 된 경우 close 이벤트 발생하며 close 이벤트 핸들러 실행된다. 

 

- 아래 코드예에서는 웹서버 시험 가능한 서버 주소를 기록했다.  내가 송신한것을 다시 보내주는 단순한 기능의 웹소켓 서버. 

 

// file : websocket.js

// WebSocket 연결 생성
const my_ws = new WebSocket("wss://ws.postman-echo.com/raw");

// 이벤트 핸들러 : 웹소켓 open  
my_ws.addEventListener("open", function (event) {
 
  document.write("WebSocket Opened<br>");
  document.write("I Send : Hi, Who are you ? I'm igotit ! . <br>");
  my_ws.send("Hi, Who are you ? I'm igotit ! . ");
});

// 이벤트 핸들러 : 웹소켓 close 
my_ws.addEventListener("close", function (event) {
  document.write("WebSocket Closed<br>");
});

// 이벤트 핸들러 : 메시지 수신 
my_ws.addEventListener("message", function (event) {
  
  document.write("Message from server : " +  event.data + "<br>");
});

 

위 자바스트립트 파일 (예 websocket.js) 를 html 파일에서 임포팅시킨다. 

 

 



<!-- 파일명 : websocket.html-->

<!DOCTYPE html>
<html>
    <head> 
    </head>

    <body>
	WebSocket Test. <br>
        <script src="websocket.js"></script>
        
    </body>
</html>

 

 

웹소켓 시험 

- 위 websocket.html 을 브라우저에서 열면 실행되어 아래 처럼 결과 보여준다. 

 

웹소켓 클라이언트 시험결과

 

 

 

연관 

 

bybit 거래소의 실시간 시세 수신 

 

bybit . 웹소켓 . 자바스크립트 실시간 시세 수신 구현 예

자바스크립트 코드 전체 HTML 삽입 미리보기할 수 없는 소스 위 코드에 있는 내용처럼 2개의 파일 ws_bybit.js , ws_bybit.html 을 동일 폴더에 만들고, 웹브라우저에서 ws_bybit.html 열면 아래 처럼 브라우

igotit.tistory.com

 

 

 


첫 등록 : 2023.10.29

최종 수정 : 

단축 주소 : https://igotit.tistory.com/4968


 

댓글



 

비트코인




암호화폐       외환/나스닥/골드       암호화폐/외환/나스닥/골드 암호화폐/외환/나스닥/골드   암호화폐/외환/나스닥/골드
     
현물 |선물 인버스 |선물 USDT       전략매니저(카피트레이딩)     롤오버 이자 없는 스왑프리계좌
( 스왑프리 암호화폐도 거래 가능 )    
MT4, MT5 , cTrader 모두 지원     FTMO 계좌 매매운용. MT4,MT5