투케이2K

32. (NodeJs) [Mac Os] [WebSocket] : ejs 자바스크립트에서 웹소켓 클라이언트 만들기 - webSocket client 본문

NodeJs

32. (NodeJs) [Mac Os] [WebSocket] : ejs 자바스크립트에서 웹소켓 클라이언트 만들기 - webSocket client

투케이2K 2024. 1. 2. 21:16
반응형

[개발 환경 설정]

개발 툴 : VS CODE

개발 언어 :NodeJs

 
 

[index.ejs : 소스 코드]

<!DOCTYPE HTML>
<html lang="ko">
<head>
    <title>WebTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    




    <!-- ================================================================================== -->
    <!-- [반응형 구조 만들기] -->
    <!-- ================================================================================== -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
    




    <!-- ================================================================================== -->
    <!-- [자바 스크립트 및 j쿼리 파일] -->
    <!-- ================================================================================== -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>





    <!-- ================================================================================== -->
    <!-- [내부 CSS 스타일 지정] -->
    <!-- ================================================================================== -->
    <style>


        /* [전체 설정 실시] */
    	* {
            font-family : 'Noto Sans KR' , sans-serif;           
            margin : 0;
            padding : 0;
    	}
    	




        /* [html , body 설정] */
        html, body{			
            width : 100%;          
            height : 100%;
            margin : 0 auto;
            padding : 0;
            border : none;         

            /* [모바일 스크롤 시 부드럽게 처리] */
            overflow:scroll-y; 
            -webkit-overflow-scrolling:touch;
        }
        /* [body 스크롤바 메인 스타일 지정] */
        body::-webkit-scrollbar {           
            width: 20px;                 
            background-color: #c1c1c1;
        }
        /* [body 스크롤바 thumb 스타일 지정] */
        body::-webkit-scrollbar-thumb {                 
            background-color: #444444;
        }
                     
    </style>
    




    <!-- ================================================================================== -->
    <!-- [내부 자바스크립트 J쿼리 이벤트 지정] -->    
    <!-- ================================================================================== -->
    <script>

        /* [dom 생성 및 이벤트 상시 대기 실시] */
        document.addEventListener("DOMContentLoaded", ready);
        function ready(){
            console.log("");
            console.log("=====================================================");
            console.log("[window ready] : [start]"); 
            console.log("=====================================================");           
            console.log("");
        }





        /* [html 최초 로드 및 이벤트 상시 대기 실시] */
        window.onload = function() {
            console.log("");
            console.log("=====================================================");
            console.log("[window onload] : [start]");
            console.log("=====================================================");
            console.log(""); 

            // [웹소켓 호출 및 확인 메소드 호출]
            clientWebSocket();

        };





        /* [html 화면 사이즈 변경 이벤트 감지] */
        window.onresize = function() {
            console.log("");
            console.log("=====================================================");
            console.log("[window onresize] : [start]");
            console.log("=====================================================");
            console.log(""); 
        };





        /* [WebSocket Client] */
        function clientWebSocket(){

            // [1]. 웹소켓 클라이언트 객체 생성
            const webSocket = new WebSocket("ws:localhost:8001");


            // [2]. 연결 이벤트 처리
            webSocket.onopen = ()=> {
                console.log("");
                console.log("=====================================================");
                console.log("[clientWebSocket] : [웹 소켓 서버와 연결 성공]");
                console.log("=====================================================");
                console.log("");

                setTimeout(() => {
                    webSocket.send("client to server : hello server");
                }, 1000);

            };

            // [3]. 메세지 수신 이벤트 처리
            webSocket.onmessage = function (event) {
                console.log("");
                console.log("=====================================================");
                console.log("[clientWebSocket] : [Sever] : " + event.data);
                console.log("=====================================================");
                console.log("");
            };

            // [4]. 연결 종료 이벤트 처리
            webSocket.onclose = function(){
                console.log("");
                console.log("=====================================================");
                console.log("[clientWebSocket] : [Connect] : Close");
                console.log("=====================================================");
                console.log("");
            };

            // [5]. 에러 발생 이벤트 처리
            webSocket.onerror = function(error){
                console.log("");
                console.log("=====================================================");
                console.log("[clientWebSocket] : [Error] : " + JSON.stringify(error));
                console.log("=====================================================");
                console.log("");
            };

        };


    </script>
    
</head>





<!-- ================================================================================== -->
<!-- [body 콘텐츠 작성] -->
<!-- ================================================================================== -->
<body>

</body>


</html>
 

[결과 출력]

 

 

반응형
Comments