socket io 사용법
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
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 오픈");
});
