socket.io


CHEATSHEET

https://socket.io/docs/v4/emit-cheatsheet

socket.emit('hello', 'world');
socket.on('hello', (arg) => console.log(arg)) // world
io.emit('hello'); // to all connected clients
socket.broadcast.emit('hello'); // 본인을 제외한 모두에게

소켓 체결시에 쿼리를 날릴 수도 있다. 클라이언트는 io({query: {...}}) 스니펫을 사용하고 서버는 다음과 같이 사용할 수 있다.

io.on('connection', socket => {
	console.log(socket.handshake.query);
});

request + response 쌍으로 주고받을 수도 있다.

// client
socket.emit('hello', 'world', (res) => console.log(res)); // got it
// server
io.on('connection', (socket) => {
	socket.on('hello', (arg, callback) => {
		console.log(arg); // world
		callback('got it');
	});
});
// server
io.of('/my-namespace').on('connection', (socket) => {
	socket.on('hello', (arg) => console.log(arg));
	// ...
});

@WebSocketGetway(80, { namespace: 'events', transports: ['websocket'] }) 어노테이션을 가지는 게이트웨이 클래스를 활용.

세 개의 인터페이스를 사용하여 들어오는 connection 요청에 대한 루틴 실행

@WebSocketGetway(80, { namespace: 'events', transports: ['websocket'] })
class GameSessionGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
	private afterInit() {}
	private handleConnection() {}
	private handleDisconnect() {}
}

서버 인스턴스를 주입받을 수 있다. socket.io 에서의 io와 동일한 타입의 객체. 서버객체는 게이트웨이 포트마다 하나씩 존재한다. 출처

	@WebSocketServer()
	io: Server;

HTTP때와 거의 비슷하게 파이프, 예외필터, 가드, 인터셉터 모두 달 수 있다.

	@UsePipes(ValidationPipe)
	@SubscribeMessage('host')
	handleEvent(client: Client, data): WsResponse<unknown> {
		const event = 'events';
		return { event, data };
	}