             resolve()
       else
         reject new Error("Not connected.")
-    )
 
 
 # Browser WebSocket

    @connection = null

    @socket.on 'connectFailed', (error) =>
      @emit 'connectFailed', error

    @socket.on 'connect', (connection) =>
      @connection = connection

      connection.on 'error', (error) =>
        @emit 'error', error

      connection.on 'message', (message) =>
        try
          @emit 'message', message.utf8Data
        catch error
          @emit 'error', error
          

      connection.on 'close', =>
        @emit 'close'

      @emit 'open'

    @socket.connect url, undefined, undefined, headers

  # Close the WebSocket if it exists
  close: ->
    @connection.close() if @connection?
    @connection = null
    @socket = null

  ping: ->
    @connection.ping() if @connection?

  send: (data) ->
    new P((resolve, reject) => 
      if @connection?
        @connection.send data, (error) ->
          if error?

{client: nodeWs, w3cwebsocket: browserWs} = require 'websocket'

class BaseWS extends EventEmitter
  constructor: (@url, @headers, timeout) ->
    super()
    @config =
      closeTimeout: timeout
      keepaliveInterval: 15000
