DEV Community

Cover image for Do not memorize code learn the concept
folaeazy
folaeazy

Posted on

Do not memorize code learn the concept

Permit me to use the word "**cramming ". When using the word 'cramming', I mean to convey that simply memorizing a particular program or piece of software source code is a bad practice. While it may help in the short term, understanding the underlying concepts is crucial for long-term retention.

Can you really memorize Windows 10 operating system source code? Hell no. Over the last few weeks, based on requests and what I saw on the internet, some tech newbies made a request for a particular line of code in a function. Surprised? Yeah, me too.

Likewise, some tech enthusiasts stick to a particular solution mostly because they don't understand the algorithm. All great developers write reusable code, don't they? Technology advances so rapidly that the next time you need the same principle, it's likely a new technique or programming language. This is when concepts come in, which is really the art of how things work. In this article, I will demonstrate this to you by creating a simple web server with three programming languages: Python, NodeJs, and C++.

When we talk about web servers, in simple terms, it is software and hardware that uses HTTP and other protocols to respond to client requests, i.e., they deliver web content to end-users over the internet through web browsers. Right from the definition, we can see we need two significant things: the software in which we will code and the hardware, in which we can use our PC for a simple server.

Now let's analyze what we need to create a web server that can handle a GET request and render a page in our program.

  1. common protocols: HTTP.
  2. Request Handler: A program to handle an incoming HTTP
    request.

  3. Route or path: To locate our files.

  4. Static files: The HTML and CSS files we want to render to the web browser.

  5. Port number: A specific number where our Server will listen to.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Web Server</title>  
    </head>
    <body>
            <h1>Basic Server</h1>
            <p>This is a Basic Web Server </p>
    </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Implementation in NodeJs

:

const http = require('http');        //http protocol
const fs = require('fs');            //file system
const path =require('path')           //path for the files


const PORT = 3500;                    //port for the server

        //Function That handles the GET request method.
function  handleRequest(req,res){
    if (req.method === 'GET'){
        if (req.url === '/'){
            fs.readFile(path.join(__dirname,'index.html'),
             function(err,data) {
                if (err){
                    res.writeHead(500);
                    res.end("Error loading page");
                }else {
                   res.writeHead(200, {'Content-Type': 'text/html'});    
                    res.end(data);
                }

            });
        }else {
            res.writeHead(404);
            res.end("404 Not FOund");

        }
    }
}
/// Creating the server with the http protocol and passing the request handler as the argument. Listening on port 3500
const server = http.createServer(handleRequest);

server.listen(PORT,function() {
    console.log(`Server listening on Port ${PORT}`);
})

Enter fullscreen mode Exit fullscreen mode

Implementation in Python:

import http.server
import socketserver

PORT = 8000  # Port number for server

# A request handler for incoming HTTP requests
class Handler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        #check if the request is for the root path
        if self.path == '/':
        # Handle GET requests by sending a response
            with open('index.html', 'rb') as fs:
             file_content = fs.read()
             self.send_response(200)
             self.send_header('Content-type', 'text/html')
             self.end_headers()
             #send File content
             self.wfile.write(file_content)

        else:
           http.server.SimpleHTTPRequestHandler.do_GET(self)

# Set up a socket server and start serving HTTP requests
with socketserver.TCPServer(("", PORT), Handler) as server:
    print("Server running on  port", PORT)
    server.serve_forever()

Enter fullscreen mode Exit fullscreen mode

Implementation in C++:

#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>


const int PORT = 8080;              //port on which the server listens     
const int BUFFER_SIZE = 1024;               //how much data that can be read and stored at once from the client socket

    //Request Handler Function
void requestHandler(int clientSocket) {
    char buffer[BUFFER_SIZE];
    int readBytes = recv(clientSocket, buffer, BUFFER_SIZE -   1, 0 );
    if (readBytes < 0) {
        std::cerr << "Error reading from  Socket\n";
        return;
    }
    buffer[readBytes] = '\0';
        //Extract the requested Url from the HTTP request
    std::string request(buffer);
    std::string requestMethod = request.substr(0,request.find(' '));
    std::string requestUrl = request.substr(request.find(' ')+1, request.find(' ', request.find(' ')+1) - request.find(' ')-1);

    std::string filePath = "." + requestUrl;
    std::ifstream file(filePath);
    if (!file.good()) {
        //file not found
        std::string notFound =
            "HTTP/1.1 404 Not Found\n"
            "Content-Type: text/plain\n"
            "Content-Length: 14\n"
            "\n"
            "404  Not Found\n";
        send(clientSocket, notFound.c_str(), notFound.length(), 0);
        close(clientSocket);
        return;
    }

    // To read the content of the file request.
    std::string fileContent;

    if (file.is_open()) {
        std:: string data;
        while(getline(file,data)) {
            fileContent += data;
        }
        file.close();
    } else {
        fileContent = "Error reading file";
    }

        // return an Http Response.
    std::string httpResponse =
        "HTTP/1.1 200 OK\n"
        "Content-Type: text/html\n"
        "Content-Length: " + std::to_string(fileContent.length()) + "\n\n"
        + fileContent; 

     //send response to the client socket
    send(clientSocket, httpResponse.c_str(), httpResponse.length(),0);
    close(clientSocket);        //close the socket
}




int main()
{
    int server_socket, client_socket;
// to store the internet address
    struct sockaddr_in serverAddress, clientAddress;        
    socklen_t clientAddressSize = sizeof(clientAddress);

    //-------------creating a new socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket < 0) {
        std::cerr << "Error creating socket"<<std::endl;
        return 1;
    }

    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = INADDR_ANY;


    if (bind(server_socket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) <  0) {
        std::cerr << "Error Binding Socket"<<std::endl;
        return 1;

    }

    if (listen(server_socket,6) < 0){
        std::cerr << "Error Listening on the Socket"<<std::endl;
        return 1;
    }

    std::cout << "Server Listening on port "<< PORT<< std::endl;


    while (true){
        client_socket = accept(server_socket, (struct sockaddr*) &clientAddress, &clientAddressSize);
        if (client_socket < 0) {
            std::cerr << "Error accepting connections\n";
            continue;
        }
        requestHandler(client_socket);
    }

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, understanding the concepts and underlying principles of programming is crucial for long-term retention and success as a software developer. Cramming or simply memorizing code may help in the short term, but it is not a sustainable approach. In this article, we demonstrated how to create a simple web server using three different programming languages: NodeJs, Python, and C++. While the syntax and implementation may differ, the concepts and principles remain the same. As technology continues to evolve rapidly, it is essential to have a solid understanding of the fundamentals to adapt and stay current in the ever-changing tech landscape.

Top comments (0)