我正在自学 Coffeescript/node,当然,唯一的方法是使用 TDD。这意味着我也在自学誓言。我认为至少有两个问题。一个是——获取 HTTP 响应的异步代码在哪里?另一个是——为什么服务器不给我回复?控制台显示“已发送请求”,但不显示“已收到请求”。
这是测试文件:
vows = require 'vows'
assert = require 'assert'
EventEmitter = require('events').EventEmitter
Server = require('./web').WebServer
Client = require('../lib/client').Client
Request = require('../lib/request').Request
PORT = 8080
SERVER = new Server PORT
SERVER.start()
CLIENT = new Client PORT, 'localhost'
REQUEST = new Request 'GET', '/'
vows
.describe('Sending a request to the server')
.addBatch
'The request is sent':
topic: ->
CLIENT.transmit(REQUEST, @callback)
return
'The response should be what the server sent back': (err, request) ->
body = ""
request.on 'response', (response) ->
response.on 'data', (chunk) -> body += chunk
assert.equal body, /Ooga/
.export(module)
这是 WebServer 对象:
Http = require('http')
exports.WebServer = class WebServer
processRequest = (request, response) ->
console.log 'Request received!'
console.log request
response.writeHead 200, {'Content-Type':'text/plain'} #, 'Content-Length':'6'}
response.write 'Ha-ha!'
response.end
constructor: (@port) ->
@server = Http.createServer processRequest
start: ->
@server.listen @port
stop: ->
@server.close()
接下来是客户端代码——也很简单。
Http = require 'http'
Request = require('./request').Request
exports.Client = class Client
constructor: (@port, @host) ->
@httpClient = Http.createClient @port, @host
@sentence = "I am a Client"
transmit: (request, callback = null) ->
req = @httpClient.request request.method, request.pathName
req.end
console.log "Request sent!"
if callback
callback(null, req)
#req.on 'response', (res) ->
# callback(null, res)
#request.on 'data', (chunk) -> callback(null, chunk)
#callback(null, request)
最后是“请求”对象。
exports.Request = class Request
constructor: (@method, @pathName) ->
method: ->
@method
pathName: ->
@pathname
responseBody: ->
@body
setResponseBody: (body) ->
@body = body
appendToResponseBody: (chunk) ->
@body += chunk
所有这一切都如此简单,以至于我真的不知道为什么服务器似乎无法正常工作。我什至不担心异步代码应该在哪里从服务器获取信息,但我也想弄清楚..