한계
- HTTP 요청과 응답으로만은 Realtime service 불가능
- Socket은 Desktop/Mobile Application은 가능하지만 Web Browser 에서는 사용 불가능
- Ajax, Polling, Web Socket 같은 다양한 기술들이 나왔지만, 문제점은 여러 웹 브라우저에서 지원 차이가 큼
Socket.IO
호환되는 웹 브라우저를 자동 선택
Install
npm install socket.io
Server 생성
// create http, socket.io server
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
server.listen(8080);
// socket server
var io = require('socket.io')(server);
Connection
Client
<!-- connect to server -->
<script>
var socket = io();
socket.on('connect', function(arg) {
console.log('server connected');
});
</script>
Server
// connect to client
io.on('connection', function(socket) {
console.log('client connected');
socket.on('disconnect', function() {
console.log('client disconnected');
});
});
Data 송수신
이벤트 기반으로 데이터를 교환
Server, Client 양측에서 데이터 송수신 가능
- 전송을 위한 이벤트 발생:
socket.emit('이벤트 이름', data)
; - 수신을 위한 이벤트 리스너:
socket.on('이벤트 이름', function(data){})
;
Send
// send data
socket.emit('send message', {message: "hello"});
// Server일 때 모든 Socket들에게 data broadcasting하려면 io.emit()을 사용
io.emit('broadcasting', {message: '브로드케스트 테스트'});
Receive
// receive data
socket.on('send message', function(data) {
console.log(data.message) // hello 출력
});
socket.on('broadcasting', function(data) {
console.log(data.message) // 브로드케스트 테스트 출력
});
Namespace와 Room
1:1 통신은 socket.emit()
, 브로드케스트 통신은 io.emit()
으로 가능
1:N 통신을 위해 Namespace와 Room을 사용
Namespace
같은 네임 스페이스에서만 메세지 송수신
- defalut namespace : /
- custom namespace : /CUSTOM-NAMESPACE
// Server
var nsp = io.of('/Custom-Namespace');
nsp.on('connection', function(socket) {
console.log('namespace client connected');
});
nsp.emit('custom-event', 'hello');
// Client
var nsp = io('http://서버주소/Custom-Namespace');
nsp.on('connect', function() {
console.log('namespace server connected');
});
nsp.on('custom-event', function(data) {
console.log(data);
});
Room
- Namespace 내의 채널
- 같은 룸에서만 데이터 교환 가능
- 룸에 입장(join), 퇴장(leave) 가능
- 서버에서만 제어 가능
// Client
socket.emit('joinRoom', {room: 1});
// Server
var room = 2;
socket.on('joinRoom', function(data) {
// 기존 방 나오기
socket.leave(room);
// 새 방 입장
room = data.room;
socket.join(room);
});
socket.on('send2room', function(data) {
io.to(room).emit('chat', {chat: "edefs"});
});
'Study > Backend' 카테고리의 다른 글
[Node.js] RESTful API (0) | 2021.09.07 |
---|---|
[Node.js] Asynchronous 흐름 제어 (0) | 2021.09.07 |
[Node.js] TDD(테스트 주도 개발 / Test Driven Development) (0) | 2021.09.04 |
[Node.js] HTTP Request (0) | 2021.09.04 |
[Node.js] Express.js (0) | 2021.09.04 |
Comment