     @_stopped = false
 
   _initParser: (callback) ->
+    # Initialize a Netstring stream parser
     nsStream = new ns.Stream @socket
 
     nsStream.on 'data', (data) =>

{EventEmitter}        = require 'events'
{BufferedWriteStream} = require 'nack/buffered'

exports.ClientRequest = class ClientRequest extends EventEmitter
  constructor: (@socket, @method, @path, headers, metaVariables) ->
    @bufferedSocket = new BufferedWriteStream @socket
    @writeable = true

    @_parseEnv headers, metaVariables
    @write JSON.stringify @env

    @socket.on 'connect', => @bufferedSocket.flush()

    @bufferedSocket.on 'drain', => @emit 'drain'
    @bufferedSocket.on 'close', => @emit 'close'

    response = new ClientResponse @socket
    response._initParser () =>
      @emit 'response', response

  _parseEnv: (headers, metaVariables) ->
    @env = {}
    @env['REQUEST_METHOD'] = @method

    {pathname, query} = url.parse @path
    @env['PATH_INFO']    = pathname
    @env['QUERY_STRING'] = query
    @env['SCRIPT_NAME']  = ""

    @env['REMOTE_ADDR'] = "0.0.0.0"
    @env['SERVER_ADDR'] = "0.0.0.0"

    if host = headers.host
      if {name, port} = headers.host.split ':'
        @env['SERVER_NAME'] = name
        @env['SERVER_PORT'] = port

    for key, value of headers
      key = key.toUpperCase().replace('-', '_')
      key = "HTTP_#{key}" unless key == 'CONTENT_TYPE' or key == 'CONTENT_LENGTH'
      @env[key] = value

    for key, value of metaVariables
      @env[key] = value

  write: (chunk) ->
    @bufferedSocket.write ns.nsWrite(chunk.toString())

  end: ->
    @bufferedSocket.end()

exports.ClientResponse = class ClientResponse extends EventEmitter
  constructor: (@socket) ->
    @client = @socket


    nsStream.on 'error', (exception) =>
      return if @_stopped
      # Flag the response as stopped
      @_stopped = true
      # Bubble the error, hopefully someone will catch it
      @socket.emit 'error', exception

    @socket.on 'end', =>
