설치
서버에 설치
yarn add socket.io
서버에 초기설정 (server.js)
const http = require('http').createServer(app);
const { Server } = require("socket.io");
const io = new Server(http);
클라이언트에 설치
yarn add socket.io-client
CDN 이용 설치시
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
클라이언트에 초기설정 (index.ejs)
var socket = io();
주의 : 서버측과 클라이언트의 버전이 같아야함.
사용
서버측
io.on('connection', function (socket) {
socket.on('user-send', function (data) {
io.emit('broadcast', data) //모든사람에게 데이터 전송
});
});
전송
io.emit("something", data)
// something 이라는 이름으로 data 를 전송
수신
socket.on("something", function(data){ console.log(data) })
// something 이라는 이름으로 날라온 정보를 data 에 격납