Source

Vesperia / client.coffee

Full commit
###
 Vesperia: A Tethealla management port proxy and api server

 Copyright 2012 Pol Cámara
 Released under the MIT license
 Check LICENSE.MIT for more details.
###

settings  = require './settings'
events = require 'events'

class Client
  connected: false
  attempts: 0
  stream: false
  events: false

  constructor: (@net, @port, @host) ->

  ###
  Initializes the client
  Example usage:
    clientInstance.initialize()
  ###
  initialize: ->
    this.stream = new this.net.Socket
    this.stream.client = this
    this.stream.connect(this.port,this.host)
    this.stream.on "error", this.onError 
    this.stream.on "data", this.onData  
    this.stream.on "connect", this.onConnect
    this.stream.on "end", this.onEnd 
    this.events = new events.EventEmitter()
    this.events.on 'message', (message) -> 
      console.log "Recieved message: '#{message}'"

  onConnect: -> 
    this.client.attempts = 1
    this.client.connected = true
    if settings.askChat
      if settings.chatLobby != ""
        this.write "205"
      else
        this.write "205" + settings.chatLobby
    console.log "Connected"

  onData: (data)  ->
    this.client.events.emit 'message', data

  onError: (err) ->
    client = this.client
    this.client.attempts++
    if this.client.attempts <= settings.maxAttempts
      # This looks a bit strange but setTimeout need to run 
      # Using a closure, and thats the way the work o coffeescriptn
      setTimeout ( ->
        client.reconnect()
      ), settings.attemptWait
    else
      this.client.attempts = 1; 

  onEnd: ->
    client = this.client
    this.client.attempts++
    setTimeout ( ->
      client.reconnect()
    ), settings.attemptWait

  reconnect: ->
    console.log("Connecting to Tethealla failed... reconnect attempt: " + this.attempts )
    this.stream.connect(this.port, this.host)

  endConnection: ->
    this.stream.close
    console.log "Socket closed"
  
module.exports.client = Client