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

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

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


    @socket.onopen =>
      @connected = true
      setImmediate => @emit 'open'

    @socket.onmessage (message) =>
      setImmediate => @emit 'message', message

    @socket.onclose =>
      setImmediate => @emit 'close'

    @socket.onerror (error) =>
      if @connected
        setImmediate => @emit 'error', error
      else
        setImmediate => @emit 'connectFailed', error

  # Close the WebSocket if it exists
  close: ->
    new P (resolve, reject) =>
      if @socket?
        @socket.onerror (error) => reject error
        @socket.onclose => resolve()
        @socket.close()
        @socket = null
      else
        resolve()

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

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