⚡app.js
const socket = io()
const welcome = document.getElementById("welcome");
const form = welcome.querySelector("form")
const room = document.getElementById("room")
room.hidden = true;
let roomName = ''
function showRoom() {
welcome.hidden = true
room.hidden = false
const h3 = room.querySelector("h3")
h3.innerText = `Room ${roomName}`
const msgForm = room.querySelector("#msg")
const nameForm = room.querySelector("#name")
msgForm.addEventListener("submit", handleMessageSubmit)
nameForm.addEventListener("submit", handleNicknameSubmit)
}
function addMessage(message) {
const ul = room.querySelector("ul")
const li = document.createElement("li")
li.innerText = message;
ul.appendChild(li)
}
function handleMessageSubmit(event) {
event.preventDefault();
const input = room.querySelector("#msg input")
const value = input.value
socket.emit("new_message", value, roomName, () => {
addMessage(`You : ${value}`)
})
input.value = ""
}
function handleNicknameSubmit(event) {
event.preventDefault();
const input = room.querySelector("#name input")
const value = input.value
socket.emit("nickname" , value)
input.value = ""
}
function handleRoomSubmit(event) {
event.preventDefault()
const input = form.querySelector("input")
socket.emit("enter_room", input.value, showRoom)
roomName = input.value
input.value = ""
}
form.addEventListener("submit", handleRoomSubmit)
socket.on("welcome" , (userNickname, newCount) => {
const h3 = room.querySelector("h3")
h3.innerText = `Room ${roomName} (${newCount})`
addMessage(`${userNickname} arrived!`)
})
socket.on("bye" , (userNickname, newCount) => {
const h3 = room.querySelector("h3")
h3.innerText = `Room ${roomName} (${newCount})`
addMessage(`${userNickname} left`)
})
socket.on("new_message" , (msg) => {
addMessage(msg)
})
socket.on("room_change" , (rooms) => {
const roomList = welcome.querySelector("ul");
roomList.innerHTML = ""
if(rooms.length === 0) {
return;
}
rooms.forEach((room) => {
const li = document.createElement("li")
li.innerText = room;
roomList.append(li)
})
})
⚡server.js
import http from "http";
import { Server } from "socket.io"
import { instrument } from "@socket.io/admin-ui";
import express from 'express';
const app = express();
app.set("view engine", "pug");
app.set("views", __dirname + "/views");
app.use("/public" , express.static(__dirname + "/public"));
app.get("/", (req,res) => res.render("home"));
app.get("/*", (req,res) => res.redirect("/"));
const httpServer = http.createServer(app)
const wsServer = new Server(httpServer, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true
}
})
instrument(wsServer, {
auth: false
})
function publicRooms() {
const {
sockets : {
adapter: {sids,rooms}
}
} = wsServer;
const publicRooms = [];
rooms.forEach((_,key) => {
if(sids.get(key) === undefined) {
publicRooms.push(key)
}
})
return publicRooms
}
function countRoom(roomName){
return wsServer.sockets.adapter.rooms.get(roomName)?.size
}
const sockets = []
const handleListen = () => console.log("Listening on http://localhost:3000");
wsServer.on("connection", (socket) => {
socket["nickname"] = "Anon"
socket.onAny((event) => {
console.log(wsServer.sockets.adapter)
console.log(`Socket Event: ${event}`)
})
socket.on("enter_room", (roomName,done) => {
done()
socket.join(roomName)
socket.to(roomName).emit("welcome", socket.nickname, countRoom(roomName))
wsServer.sockets.emit("room_change", publicRooms())
})
socket.on("disconnecting" , () => {
socket.rooms.forEach(room => socket.to(room).emit("bye" , socket.nickname), countRoom(room) -1 )
})
socket.on("disconnect" , () => {
wsServer.sockets.emit("room_change" , publicRooms())
})
socket.on("new_message" , (msg,room,done) => {
socket.to(room).emit("new_message", `${socket.nickname}: ${msg}`);
done()
})
socket.on("nickname", (nickname) => (socket["nickname"] = nickname))
})
httpServer.listen(3000, handleListen);
개열심히 쳤는데 니코 쌤 또 다지우고 리스타트하네요
중간 코드 저장용으로 올립니다..
반응형
'zoom websocket' 카테고리의 다른 글
[zoom clone] 환경 설정 및 websocket 사용해보기 (1) | 2022.12.19 |
---|