Skip to content

Socket.io 정리

Heesun Kim edited this page Nov 14, 2019 · 7 revisions

1. WebSocketμ΄λž€?

  • WebSocket 은 μ‚¬μš©μžμ˜ λΈŒλΌμš°μ €μ™€ μ„œλ²„ μ‚¬μ΄μ˜ 동적인 μ–‘λ°©ν–₯ μ—°κ²° 채널을 κ΅¬μ„±ν•˜λŠ” HTML5 ν”„λ‘œν† μ½œμ΄λ‹€.

2. Http톡신과 Socketν†΅μ‹ μ˜ 차이

  • Http : Client의 μš”μ²­(Request)이 μžˆμ„ λ•Œλ§Œ μ„œλ²„κ°€ 응닡(Response)ν•˜μ—¬ ν•΄λ‹Ή 정보λ₯Ό μ „μ†‘ν•˜κ³  κ³§λ°”λ‘œ 연결을 μ’…λ£Œν•˜λŠ” 방식
  • socket : Server와 Clientκ°€ νŠΉμ • Portλ₯Ό 톡해 μ‹€μ‹œκ°„μœΌλ‘œ μ–‘λ°©ν–₯ 톡신을 ν•˜λŠ” 방식

3. socket.ioλž€?

  • socket.ioλž€ μ‹€μ‹œκ°„μœΌλ‘œ μƒν˜Έμž‘μš©ν•˜λŠ” μ›Ή μ„œλΉ„μŠ€λ₯Ό λ§Œλ“œλŠ” 기술인 μ›Ήμ†ŒμΌ“μ„ μ‰½κ²Œ μ‚¬μš©ν•  수 있게 ν•΄μ£ΌλŠ” λͺ¨λ“ˆμ΄λ‹€.
  • κ°•λ ₯ν•œ Cross-platform WebSocket API이닀.

4. socket으둜 ν†΅μ‹ ν•˜κΈ°

server

  1. io.emit(β€˜event_name’, msg) : μ ‘μ†λœ λͺ¨λ“  ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œ λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œλ‹€.
  2. socket.emit(β€˜event_name’, msg) : λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œ ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œλ§Œ λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œλ‹€.
  3. socket.broadcast.emit(β€˜event_name’, msg) : λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œ ν΄λΌμ΄μ–ΈνŠΈλ₯Ό μ œμ™Έν•œ λͺ¨λ“  ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œ λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œλ‹€.
  4. io.to(id).emit(β€˜event_name’, data) : νŠΉμ • ν΄λΌμ΄μ–ΈνŠΈμ—κ²Œλ§Œ λ©”μ‹œμ§€λ₯Ό μ „μ†‘ν•œλ‹€.

client

<script src='/socket.io/socket.io.js'></script>

let socket = io();

socket.emit('login', {
      name: "bella"
});

socket.on('chat', (data) => {
      console.log(data);
});
  1. μœ„μ˜ μ½”λ“œμ²˜λŸΌ socket을 μ—°κ²°ν•˜κ³  emit을 ν•˜λ©΄ server에 dataλ₯Ό 보내고 onν•˜λ©΄ event_nameλ³„λ‘œ 받을 수 μžˆλ‹€.
Clone this wiki locally