1. 何为服务器
服务器是某种长期运行,等待请求资源的应用程序
2. 常见Web应用架构
3. 如何创建web服务器
Web服务器是使用HTTP协议,等待客户端连接后请求资源的驻守应用程序;HTTP协议是应用层的协议,在传输层依然是使用TCP或者UDP协议,一般来说是使用Socket来绑定TCP或者UDP,总的来说创建服务器就是创建一个Socket:
创建服务器的流程:
(1)创建Socket
(2)为Socket绑定参数
(3)Socket等候请求
(4)处理请求,返回资源
(5)关闭资源
4. 使用Node.js创建服务器
server.js
var http = require(‘http‘);var fs = require(‘fs‘);var url = require(‘url‘); ?// 创建服务器http.createServer( function (request, response) { ????// 解析请求,包括文件名 ??var pathname = url.parse(request.url).pathname; ?????// 输出请求的文件名 ??console.log("Request for " + pathname + " received."); ?????// 从文件系统中读取请求的文件内容 ??fs.readFile(pathname.substr(1), function (err, data) { ?????if (err) { ????????console.log(err); ????????// HTTP 状态码: 404 : NOT FOUND ????????// Content Type: text/plain ????????response.writeHead(404, {‘Content-Type‘: ‘text/html‘}); ?????}else{ ?????????????????????// HTTP 状态码: 200 : OK ????????// Content Type: text/plain ????????response.writeHead(200, {‘Content-Type‘: ‘text/html‘}); ?????????????????????// 响应文件内容 ????????response.write(data.toString()); ?????????????} ?????// ?发送响应数据 ?????response.end(); ??}); ??}).listen(8080); // 控制台会输出以下信息console.log(‘Server running at http://127.0.0.1:8080/‘);
Node.js已经封装好了创建服务器的函数,可直接调用
5. 模拟客户端发送请求
client.js
var http = require(‘http‘); // 用于请求的选项var options = { ??host: ‘localhost‘, ??port: ‘8080‘, ??path: ‘/index.html‘ ?}; // 处理响应的回调函数var callback = function(response){ ??// 不断更新数据 ??var body = ‘‘; ??response.on(‘data‘, function(data) { ?????body += data; ??}); ?????response.on(‘end‘, function() { ?????// 数据接收完成 ?????console.log(body); ??});}// 向服务端发送请求var req = http.request(options, callback);req.end();
Node.js创建服务器和模拟客户端请求
原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/10525119.html