Namespace

✒️ 2025-05-26 14:03 내용 수정


하나의 공유된 연결을 통해 어플리케이션의 로직을 세분화할 수 있도록 하는 커뮤니케이션 채널

// main namespace "/"
io.on("connection", (socket) => {
	console.log("main namespace");
});

// 위와 동일하다
io.of("/").on("connection", (socket) => {
	console.log("main namespace");
});
// custom namespace
const newName = io.of("/specific-namespace");
newName.on("connection", (socket) => {
	console.log("new namespace");
})
const socket = io(); // main namespace로, io("/")도 동일하다.
const newNameSocket = io("/newName"); // newName namespace

특징

// 이벤트 핸들러
io.of("/test").on("connection", (socket) => {
	socket.on("test:hello", () => {
		console.log("this is test");
	});
});

io.of("/exam").on("connection", (socket) => {
	socket.on("exam:hello", () => { // test namespace와는 다른 event 핸들러
		console.log("this is exam");
	});
});
// Room
const testName = io.of("/test");

testName.on("connection", (socket) => {
	socket.join("chatroom");
	testName.to("chatroom").emit("등장!");
});

const examName = io.of("/exam");

examName.on("connection", (socket) => {
	socket.join("chatroom"); // test namespace와는 다른 room이다.
	examName.to("chatroom").emit("두등등장!");
});
// 미들웨어
const testName = io.of("/test");

testName.use((socket, next) => { // 미들웨어 사용 시 use로 작성
	// socket이 testName에 접근 가능한 상태여야 함
	next();
});

const examName = io.of("/exam");

examName.use((socket, next) => {
	// socket이 examName에 접근 가능한 상태여야 함
	next();
});