Jump To …

clients.coffee

url			= require 'url'
sys			= require 'sys'
Events		= require 'events' 
Client		= require 'client'
Log			= require 'log'

Clients

Clients module is one of the core server components. Its responsible to hold the list of all clients which are connected to the server. Its able to broadcast message to everybody connected.

Clients = module.exports = () ->
	process.EventEmitter.call(this)
	@count = 0

sys.inherits(Clients, Events.EventEmitter)

Connect

Method called if upgrade request was generated by underlaying http.Server. In order to connect new user to the server we have to validate if client request contain all necessary headers to be able to start handshake process. If everything is ok handshake process is started in order to establish communication.

If there is anything wrong with request headers the client is closed.

Clients.prototype.connect = (client) ->
	if client.request.method is "GET" and 
	client.request.headers.upgrade.toLowerCase() is 'websocket' and 
	client.request.headers.connection.toLowerCase() is 'upgrade'
		@list = {} unless @list?
		

Dont add new client if its already connected.

		if @list[client.sid]?
			return
		
		@list[client.sid] = client
		@count++

		client.addListener 'data', (client, data) =>
			@emit 'data', client, data
		
		client.addListener 'ready', (client) =>
			console.log Log.greenify('[clients]') + ' new connection'
			@emit 'ready', client
		
		client.handshake()
	else
		client.close()

Disconnect

Disconnect client from the server.

Clients.prototype.disconnect = (client) ->
	client.close()
	delete @list[client.sid]
	@count--

DisconnectAll

Close connection for all clients on the server.

Clients.prototype.disconnectAll = () ->
	(@list[sid].close()
	delete @list[sid]) for sid of @list
	@count = 0

Broadcast

Send the message to all connected clients. Message is sent to all clients connected to server which are connected and handshaked.

Clients.prototype.broadcast = (data) ->
	(if @list[sid].state == Client.STATUS_READY
		@list[sid].send(data)) for sid of @list