[]
Server 클래스는 js-collaboration의 핵심 구성 요소로, 클라이언트 연결과 메시지 흐름을 관리합니다. 이 문서에서는 해당 클래스의 기능과 사용 방법을 소개합니다.
Server 클래스 자체에는 비즈니스 로직이 포함되어 있지 않습니다. 이 클래스는 클라이언트 연결, 메시지, 연결 해제 이벤트를 수신하고, 훅(hooks) 및 미들웨어(middleware) 메커니즘을 통해 개발자가 처리할 수 있도록 위임하는 역할만 수행합니다.
미들웨어(Middleware): 인증, 권한 검증과 같이 연결 또는 메시지 흐름을 가로채(intercept) 처리하는 데 사용됩니다.
훅(Hooks): 연결 수립이나 메시지 수신과 같은 이벤트를 감지(listen)하여, 워크플로에 영향을 주지 않고 사용자 정의 로직을 실행하는 데 사용됩니다.
개발자는 미들웨어와 훅을 등록하여 비즈니스 로직을 구현하며, 서버는 오직 이벤트 디스패처 역할만 수행합니다.

on)연결, 메시지, 연결 해제와 같은 서버 라이프사이클 이벤트를 수신합니다.
일괄 등록(Batch Registration):
server.on({
connect: ({ connection }) => {
console.log(`${connection.id} connected`);
},
message: ({ data, type }) => {
console.log(`Received message: ${data} (type: ${type})`);
},
disconnect: ({ connection }) => {
console.log(`${connection.id} disconnected`);
}
});개별 등록(Individual Registration):
server.on('connect', ({ connection }) => {
console.log(`${connection.id} connected`);
});
server.on('message', ({ data, type }) => {
console.log(`Received message: ${data} (type: ${type})`);
});
server.on('disconnect', ({ connection }) => {
console.log(`${connection.id} disconnected`);
});훅은 워크플로를 가로채지 않으며, 부가적인 로직을 실행하는 용도로만 사용됩니다.
use)이벤트 처리 전에 인증이나 로깅과 같은 가로채기(interception) 로직을 실행합니다.
server.use({
connect: async (context, next) => {
if (context.connection.auth.token === 'valid-token') {
await next();
} else {
await next('Authentication failed');
}
},
message: async ({ data }, next) => {
console.log('message:', data);
}
});미들웨어에 대한 자세한 내용은 다음을 참고하세요:
useFeature)useFeature 메서드는 미들웨어와 훅을 동시에 등록할 수 있게 해줍니다. OT(Operational Transformation)나 Presence(사용자 온라인 상태)와 같은 확장 기능은 기능(feature) 형태로 제공됩니다.
import { documentFeature } from '@mescius/js-collaboration-ot';
server.useFeature(documentFeature());export interface IFeature {
middlewares?: IMiddlewares;
hooks?: IHooks;
}미들웨어를 사용한 인증 및 권한 검증
참고: 사용자 인증 및 권한
훅을 사용한 이벤트 처리
server.on({
enterRoom: ({ connection, roomId }) => {
console.log(`${connection.id} joined ${roomId}`);
},
message: ({ connection, roomId, data }) => {
console.log(`Received message from ${connection.id}: ${data}`);
console.log(`Broadcasting message to ${roomId}: ${data}`);
connection.broadcast(data);
},
leaveRoom: ({ connection, roomId }) => {
console.log(`${connection.id} left ${roomId}`);
}
});클라이언트로 메시지 전송/브로드캐스트: Server Connection Class
미들웨어 메커니즘에 대한 상세 설명: Server Middleware
다중 서버 배포 시: Multiple Servers Deployment