socket.io

milmil·2022년 10월 26일
0

노드와 나

목록 보기
7/8

웹소켓(Websocket)은 http와 구별되는 통신 프로토콜이다. 양방향 통신을 위해 사용한다.

websocket은 html5 표준 기술이며 socket.io는 라이브러리
브로드캐스팅이 가능함! (일부 클라이언트에만 데이터 전송)

아주 간단한 공식 문서에 있는 채팅 예제를 프론트엔드만 따로 분리해서 만들어본다.

node프로젝트를 만들고 socket-ioexpress설치.

app.js

import http from 'http';
import { Server } from 'socket.io';
import express from 'express';

const app = express();

//socket.io 지원을 위해 http로 서버 초기화
const server = http.createServer(app);

//웹소켓 서버 초기화, cors설정
const io = new Server(server, {
  cors: {
    origin: ['http://localhost:5000'],
  },
});

//connection 이벤트 발생하면 소켓 생성되고 콜백함수 실행됨
io.on('connection', (socket) => {
  console.log('user connected');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  //커스텀 이벤트
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
    console.log('message: ' + msg);
  });
});

// app.listen이 아닌 http.listen를 사용한다.
server.listen(3001, () => {
  console.log('started server');
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body {
        margin: 0;
        padding-bottom: 3rem;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
      }

      #form {
        background: rgba(0, 0, 0, 0.15);
        padding: 0.25rem;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        height: 3rem;
        box-sizing: border-box;
        backdrop-filter: blur(10px);
      }
      #input {
        border: none;
        padding: 0 1rem;
        flex-grow: 1;
        border-radius: 2rem;
        margin: 0.25rem;
      }
      #input:focus {
        outline: none;
      }
      #form > button {
        background: #333;
        border: none;
        padding: 0 1rem;
        margin: 0.25rem;
        border-radius: 3px;
        outline: none;
        color: #fff;
      }

      #messages {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }
      #messages > li {
        padding: 0.5rem 1rem;
      }
      #messages > li:nth-child(odd) {
        background: #efefef;
      }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action=""><input id="input" autocomplete="off" /><button>Send</button></form>
  </body>
</html>

복사붙여넣기함

클라이언트에서는 socket-io-client설치

(webpack을 사용했는데, 사용하지 않을 경우

<script type="module">
  ...
</script>

이렇게 html에 넣어도 된답니다

index.js

import './assets/style.scss';
import { io } from 'socket.io-client';

const form = document.getElementById('form');
const input = document.getElementById('input');

const socket = io('http://localhost:3001');

form.addEventListener('submit', function (e) {
  e.preventDefault();
  if (input.value) {
    socket.emit('chat message', input.value);
    input.value = '';
  }
});

socket.on('chat message', function (msg) {
  const item = document.createElement('li');
  item.textContent = msg;
  messages.appendChild(item);
  console.log(msg);
  window.scrollTo(0, document.body.scrollHeight);
});

submit 이벤트가 발생하면 'chat message' 이벤트가 발생하고 두번째 인자로 인풋 밸류를 보내줌.

그리고 chat message 이벤트가 발생하면, 메세지를 받아서 모든 소켓에 뿌려준다


db에 저장하지 않는 단순 채팅은 이렇게 간단하게 만들어볼 수 있었다

참고: https://socket.io/get-started/chat

profile
쓰고 싶은 글만 씀

0개의 댓글