The Pursuit of Happyness

반응형

실행환경 Ubuntu 14.04 LTS / node v0.10.25


이번에는 events 모듈을 이용한 채팅서버 코드이다.

events 모듈을 이용하여 원하는 명령어에 대한 동작을 다음과 같이 구현하면 된다.

event를 전송하는 channel 객체를 생성하고, 채널 객체에 clients 에는 소켓들을, subscriptions 에는 각 클라이언트에 전달하는 메써드를 지정한다.

클라이언트 연결시에는 'join' 이벤트가, 연결 종료시에는 'leave' 이벤트가 처리된다.


var events = require('events');
var net = require('net');

var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};

channel.on('join',
        function(id, client) {
                this.clients[id] = client;
                this.subscriptions[id] = function(senderId, message) {
                        if (id != senderId) {
                                this.clients[id].write(message);
                        }
                }
                this.on('broadcast', this.subscriptions[id]);
        }
);

channel.on('leave',
        function(id) {
                channel.removeListener('broadcast', this.subscriptions[id]);
                channel.emit('broadcast', id, id + " has left the chat.\n");
        }
);

var server = net.createServer(
        function(client) {
                var id = client.remoteAddress + ':' + client.remotePort;
                channel.emit('join', id, client);
                client.on('data',
                        function(data) {
                                channel.emit('broadcast', id, data.toString());
                        }
                );
                client.on('close',
                        function() {
                                channel.emit('leave', id);
                        }
                );
        }
);
server.listen(3000);


반응형