socket.io 맛보기

Taesol Kwon·2020년 8월 14일
0

socket.io 란?

socket.io는 서버와 클라이언트 간에 양방향 통신을 가능하게 해주는 모듈이다. 통신을 할때, 각 브라우저에 대해서 websocket, pooling, streaming, flash socket 등에서 가장 적절한 방법을 찾아 통신을 가능케 한다.

언제 사용해..?

보통 활용되는 곳은 채팅, binary 스트리밍, 실시간 분석 등이다.

간단 예제

예시로는 1:1 채팅을 들어보겠다.
찾아볼때마다 jQuery로만 예시가 나와있어 jQuery를 1도 모르는 나는 vanila JS를 이용해 만들어보았다.
하지만 이를 사용하기 위해서는 node.js를 다뤄야만 한다 ㅠㅠ 공부하자 ㅠㅠ

// index.js
// 서버측 코드
const app = require("express")();
const http = require("http").createServer(app);
const io = require("socket.io")(http);

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

// on은 이벤트를 받아오는(get) 함수?이다.
io.on("connection", (socket) => {
  socket.on("chat", (msg) => {
    console.log("message: " + msg.message);
    
    // emit은 이벤트를 보내는(post) 함수?이다.
    io.emit("chat", msg.message);
  });
});

http.listen(3000, () => {
  console.log("listening on *:3000");
});
// index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        font: 13px Helvetica, Arial;
      }
      form {
        background: #000;
        padding: 3px;
        position: fixed;
        bottom: 0;
        width: 100%;
      }
      form input {
        border: 0;
        padding: 10px;
        width: 90%;
        margin-right: 0.5%;
      }
      form button {
        width: 9%;
        background: rgb(130, 224, 255);
        border: none;
        padding: 10px;
      }
      #messages {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }
      #messages li {
        padding: 5px 10px;
      }
      #messages li:nth-child(odd) {
        background: #eee;
      }
    </style>
  </head>
  <script src="/socket.io/socket.io.js"></script>

  <body>
    <div id="messages"></div>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" splaceholder="입력하시오" /><button
        id="send"
      >
        Send
      </button>
    </form>
  </body>
  <script>
    const message = document.querySelector("#m");
    const sendBtn = document.getElementById("send");
    const messages = document.getElementById("messages");

    const socket = io();

    sendBtn.addEventListener("click", (e) => {
      e.preventDefault(); 
      socket.emit("chat", {
        message: message.value,
      });
      message.value = "";
    });

    socket.on("chat", (msg) => {
      const li = document.createElement("li");
      messages.appendChild(li).innerText = msg;
    });
  </script>
</html>

위에 html을 이용하거나 아래 chat.js 파일을 html에 import해서 써도 된다.

// chat.js
// 클라이언트 
const socket = io.connect("http://localhost:3000");

const message = document.getElementById("m");
const sendBtn = document.getElementById("send");
const messages = document.getElementById("messages");

sendBtn.addEventListener("click", () => {
  socket.emit("chat", {
    message: message.value,
  });
  message.value = "";
});

socket.on("chat", (msg) => {
  messages.innerHTML += "<li>" + msg + "</li>";
});

결과물

위와 같이 작성하면 간단하게 1:1 채팅을 구현할 수 있다. 아직 맛보기 정도로만 만져봤기에 다음번에는 Vue를 이용해 n:1 채팅 기능을 구현해 보도록 하겠다:)👋

profile
사진촬영을 좋아하는 프론트엔드 개발자입니다.

0개의 댓글