[TIL] Socket IO를 이용한 간단한 메시지 앱 구현

김민재·2024년 4월 9일

TIL

목록 보기
149/194

socket io 사용법

1. 필요한 모듈 설치

  • client 폴더에 socket cdn 불러오기

    <!DOCTYPE html>
    <html lang="ko">
     <head>
       <meta charset="UTF-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1.0" />
       <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
       <script src="index.js" defer></script>
       <title>Document</title>
     </head>
     <body style="height: 100vh"></body>
    </html>
    
  • server 폴더에 socket 모듈 설치
    npm i socket.io

2. socket io를 이용해서 로직을 구현하자

  • client 폴더

    // index.html
    <!DOCTYPE html>
    <html lang="ko">
     <head>
       <meta charset="UTF-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1.0" />
       <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
       <script src="index.js" defer></script>
       <title>Document</title>
     </head>
     <body>
       <ul>
         <input type="text" name="" id="" placeholder="message" />
         <button>send</button>
       </ul>
     </body>
    </html>
    
     //index.js 
      const socket = io("ws://localhost:3000");
    
    // 서버에서 데이터 받는 걸 on으로 받는다.
    socket.on("message", (text) => {
     const el = document.createElement("li");
     el.innerHTML = text;
    
     document.querySelector("ul").appendChild(el);
    });
    
    document.querySelector("button").onclick = () => {
     const text = document.querySelector("input").value;
    
     // 클라이언트에서 데이터 보내는 걸 emit으로 보낸다.
     socket.emit("message1", text);
    };
    
  • server 폴더

 const http = require("http").createServer();

const io = require("socket.io")(http, {
  cors: { origin: "*" },
});

// socket 연결
io.on("connection", (socket) => {
  console.log("a user connected");

  // client에서 오는 걸 on으로 받아준다.
  socket.on("message1", (message) => {
    // 누가 보냈는지는 socket.id에 있다.
    // client로 emit으로 보낸다.
    io.emit("message", `${socket.id.substr(0, 2)} said ${message}`);
  });
});

http.listen("3000", () => {
  console.log("3000 오픈");
});
  1. 새시크릿창과 기존 라이브 창과 소통을 해보자.

profile
개발 경험치 쌓는 곳

0개의 댓글