A web server is a software application that serves web pages to users upon request. It handles HTTP requests from clients (typically web browsers) and delivers HTML documents, images, stylesheets, scripts, and other web resources back to the clients.
Web servers are a critical component of the web infrastructure, enabling the delivery of content and services over the internet. They listen for incoming HTTP requests, process them, and return the appropriate HTTP responses. Web servers can serve static content (like HTML and images) and dynamic content generated by web applications.
Example:
Here is an example of a simple web server implemented in Node.js using the http
module:
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body "Hello, World!"
res.end('Hello, World!\n');
});
// Server listens on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Explanation of the Example:
- Creating the Server: The
http.createServer
function creates an HTTP server that listens for requests. The callback function is called whenever a request is received. - Setting Headers: The
res.writeHead
function sets the HTTP status code and headers for the response. - Sending the Response: The
res.end
function sends the response body and signals that the response is complete. - Listening on a Port: The
server.listen
function makes the server listen on the specified port (3000 in this case) and starts accepting connections.