Socket.io을 사용해서 서버와 클라이언트 통신하기

dev_jubby·2022년 9월 22일
0

Node.js

목록 보기
8/8

WebSocket을 알아보고, socket.io를 사용해서 서버와 클라이언트 통신하기


💡 소켓(Socket) 이란?

프로세스가 네트워크로 데이터를 내보내거나 데이터를 받기 위한 실제적인 창구역할을 하는 것으로, 서버와 클라이언트를 연결해주는 도구이다.

  • 서버 : 클라이언트 소켓의 연결 요청을 대기하고, 연결 요청이 오면 클라이언트 소켓을 생성해 통신을 가능하게 하는 것
    • socket() : 소켓 생성 함수
    • bind() : ip와 port 번호 설정 함수
    • listen() : 클라이언트의 요청에 수신 대기열을 만드는 함수
    • accept() : 클라이언트와의 연결을 기다리는 함수
  • 클라이언트: 실제로 데이터 송수신이 일어나는 곳
    • socket() : 소켓을 여는 함수
    • connect() : 통신할 서버의 설정된 ip와 port 번호에 통신을 시도하는 함수
    • 통신 시도 시, 서버가 accept() 함수를 이용해 클라이언트의 socket descriptor를 반환
    • 이를 통해 클라이언트와 서버가 서로 read() write()를 반복하며 통신


💡 웹소켓(WebSocket) 이란?

양방향 소통을 위한 프로토콜로, HTML5 웹 표준 기술이며 빠르게 작동하며 통신할 때 아주 적은 데이터를 이용한다. 이벤트를 단순히 듣고, 보내는 것만 가능하다.



💡 Socket.io ?

양방향 통신을 하기 위해 웹소켓 기술을 활용하는 JavaScript 라이브러리로, 방 개념을 이용해 일부 클라이언트에게만 데이터를 전송하는 브로드캐스팅이 가능하다.



🔎 Socket.io 사용하기

먼저 초기화 및 필요한 dependeny를 설치한다.

npm init
npm install express socket.io


💻 Client 코드 구현

<!-- index.html -->
<html>
    <head>
        <!-- socket.io -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"></script>
    </head>

    <body>
        <h1>Hello World!</h1>
        <button type="button" onclick="btnClick('hello');">hello</button>
        <button type="button" onclick="btnClick('study');">study</button>
        <button type="button" onclick="btnClick('bye');">bye</button>
        <div id="contents" style="position:relative; margin-top: 20px; font-weight: 700;"></div>

        <script>
            var socket = io.connect();
            
            socket.on("connect", function(){ 
                console.log("server connected");
            });

            function btnClick(data){
                socket.emit("click", data);
            };

            socket.on("clickResponse", function(data) {
                console.log(data);
                var contents = document.getElementById('contents');
                contents.innerText = data;
            });
        </script>
    </body>
</html>


🔧 Server 코드 구현

/* index.js */
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);


app.get("/", function(req, res){
    console.log("client");
    res.sendFile( __dirname + "/index.html");
});

io.on("connection", function(socket){ // on 연결이 됌
    console.log("connected");
    // emit(): write, on(): read
    socket.emit("hello", "server hello"); // 같은 이벤트명을 찾아간다(클라이언트).
    socket.on("click", function(data) {
        console.log("client click:", data);
        socket.emit("clickResponse", 'success'); // socket: 현재 연결하는 그 클라이언트에만 보낸다!!
        io.emit("clickResponse", "io success"); // io: 모든 클라이언트에게 보낸다!!
    })
});


http.listen( 8000, function() {
    console.log("Server port :", 8000);
});


🎨 동작 View

profile
신입 개발자 쥬비의 기술 블로그 입니다.

0개의 댓글