我有客户端服务器编程课程的作业,它希望我创建多客户端Web服务器。但规则是web服务器必须实现HTTP版本1.0协议,在该协议中,为web页面的每个组件发送单独的HTTP请求。不幸的是,我只知道使用Node.js。我知道C,但它已经很久了(大约10年前),只做算术运算等非常基本的编程,使用字符串和数组,而不是C中的OOP。
那么问题来了,如何在Node.js中创建HTTP/1.0协议的web服务器呢?
目前,我的笔记本电脑上安装了node v.10.15.1(使用macos)。我尝试过http和net模块,但找不到如何配置协议以使用http/1.0
我们需要首先需要http模块,并将我们的服务器绑定到我们侦听的端口。在索引.js内部:
// content of index.js
const http = require('http')
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Its Your Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
所以让我们从开始
$ node index.js