Web服務器通常指網站服務器,是指駐留於因特網上某種類型計算機的程序,Web服務器的基本功能就是提供Web信息瀏覽服務。它只需支持HTTP協議、HTML文檔格式及URL,與客戶端的網絡瀏覽器配合。php
大多數 web 服務器都支持服務端的腳本語言(php、python、ruby)等,並經過腳本語言從數據庫獲取數據,將結果返回給客戶端瀏覽器。html
目前最主流的三個Web服務器是Apache、Nginx、IIS。node
Client - 客戶端,通常指瀏覽器,瀏覽器能夠經過 HTTP 協議向服務器請求數據。python
Server - 服務端,通常指 Web 服務器,能夠接收客戶端請求,並向客戶端發送響應數據。web
Business - 業務層, 經過 Web 服務器處理應用程序,如與數據庫交互,邏輯運算,調用外部程序等。數據庫
Data - 數據層,通常由數據庫組成。瀏覽器
Node.js 提供了 http 模塊,http 模塊主要用於搭建 HTTP 服務端和客戶端,使用 HTTP 服務器或客戶端功能必須調用 http 模塊,代碼以下:ruby
var http = require('http');
如下是演示一個最基本的 HTTP 服務器架構(使用8081端口),建立 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(8081); // 控制檯會輸出如下信息 console.log('Server running at http://127.0.0.1:8081/');
接下來咱們在該目錄下建立一個 index.htm 文件,代碼以下:網絡
<html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html>
執行 server.js 文件:
$ node server.js Server running at http://127.0.0.1:8081/
接着咱們在瀏覽器中打開地址:http://127.0.0.1:8081/index.htm,顯示以下圖所示:
執行 server.js 的控制檯輸出信息以下:
Server running at http://127.0.0.1:8081/ Request for /index.htm received. # 客戶端請求信息
Node 建立 Web 客戶端須要引入 http 模塊,建立 client.js 文件,代碼以下所示:
var http = require('http'); // 用於請求的選項 var options = { host: 'localhost', port: '8081', path: '/index.htm' }; // 處理響應的回調函數 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();
新開一個終端,執行 client.js 文件,輸出結果以下:
$ node client.js <html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html>
執行 server.js 的控制檯輸出信息以下:
Server running at http://127.0.0.1:8081/ Request for /index.htm received. # 客戶端請求信息