DEV Community

meenachan
meenachan

Posted on

A Magical Guide to Building Your Own Web Server - For Budding Coders! πŸš€βœ¨

Introduction:
Hello, little coding wizards!
Today, we're embarking on a magical journey to create our very own web server. It's like having a magic wand that makes the internet dance to our tunes! 🌐✨

Section 1: Setting Up Your Enchanted Castle 🏰
In the coding kingdom, every wizard needs a castle! Our castle is a special folder called "www," where we keep treasures to share with our friends. Let's start by creating this magical castle.

// Enchanted Castle Setup
private static String ROOT_DIRECTORY = "www";
Enter fullscreen mode Exit fullscreen mode

Imagine your computer as a magical castle. We're creating a folder called "www" inside the castle. This is where we'll keep all our magical web treasures!

Section 2: Magical Portal - Starting Your Adventure πŸš€
Now, let's create a magical portal (server socket) on port 80. This portal will help us communicate with friends on the internet.

// Magical Portal - Starting Your Adventure
public static void main(String[] args) {
    // ... (Allow specifying the location of the www folder)
    ServerSocket serverSocket = new ServerSocket(80);
    while (true) {
        Socket clientSocket = serverSocket.accept();
        new Thread(() -> handleRequest(clientSocket)).start();
    }
}
Enter fullscreen mode Exit fullscreen mode

Think of the internet as a magical world. We're creating a portal (like a door) on our computer that listens on port 80. When a friend knocks on this door (client connects), we welcome them and handle their requests!

Section 3: Welcoming Magical Creatures - Handling Requests 🌟
When a magical creature (client) knocks, we welcome them and handle their requests in a new thread.

// Welcoming Magical Creatures - Handling Requests
private static void handleRequest(Socket clientSocket) {
    // ... (Opening scrolls for communication with the magical creature)
    String request = in.readLine();
    String requestedPath = getRequestPath(request);

    if (requestedPath.endsWith(".cgi")) {
        serveCgiScript(requestedPath, writer);
    } else {
        serveHtmlFile(requestedPath, writer);
    }
    clientSocket.close();
}
Enter fullscreen mode Exit fullscreen mode

When a friend (client) comes to visit, we read their request on a magical scroll. Depending on what they ask for, we decide whether to share a magical tale (HTML file) or perform a special spell (CGI script)!

Section 4: Extracting Desires - Getting the Requested Path 🧭
Let's create a magical function to extract the desired path from the creature's request.

// Extracting Desires - Getting the Requested Path
private static String getRequestPath(String request) {
    String[] parts = request.split(" ");
    return (parts.length >= 2) ? parts[1] : "/";
}
Enter fullscreen mode Exit fullscreen mode

We use a magical function to understand what our friend is asking for. The function extracts the path from their request, like telling us which book they want from our magical library!

****Section 5: Sharing Magical Tales - HTML Files πŸ“–
We can share magical tales (HTML files) from our enchanted castle. If a friend asks for a specific tale, we find it and share the wonder!

// Sharing Magical Tales - HTML Files
private static void serveHtmlFile(String requestedPath, PrintWriter writer) throws IOException {
    // ... (Constructing the magical path to the tale based on the creature's request)
    try (BufferedReader fileReader = new BufferedReader(new FileReader(file))) {
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html");
        writer.println();

        // Sending the magical content of the tale to the creature
        String line;
        while ((line = fileReader.readLine()) != null) {
            writer.println(line);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

When a friend asks for a magical tale, we find the tale in our enchanted library (HTML file) and share it with them. The friend can now see the magical content in their browser!

Section 6: Special Spells - CGI Scripts! πŸ§™β€β™‚οΈ
For friends who love special spells (CGI scripts), we take them to a secret room and perform magical spells to create something special!

// Special Spells - CGI Scripts
private static void serveCgiScript(String requestedPath, PrintWriter writer) throws IOException {
    // ... (Constructing the magical path to the script based on the creature's request)
    try {
        // Performing the special spell by executing the CGI script
        // ... (Sending the magical output of the special spell to the creature)
    } catch (IOException e) {
        // If there is an issue with the special spell, sending a message of internal error to the creature
        writer.println("HTTP/1.1 500 Internal Server Error");
        writer.println("Content-Type: text/plain");
        writer.println();
        writer.println("500 Internal Server Error");
    }
}
Enter fullscreen mode Exit fullscreen mode

Some friends want more than just talesβ€”they want special spells! CGI (Common Gateway Interface) scripts are like magical spells that can do amazing things. In our enchanted castle, we have a special room for these spells. When a friend asks for a special spell by requesting a path that ends with ".cgi," we perform the spell by executing the CGI script. The result is a magical output that we share with our friend.

What is CGI?
CGI is like a magic spellbook for web servers. It allows us to perform special actions on the server and create dynamic content. Instead of just sharing fixed tales (HTML files), CGI lets us perform spells (scripts) that can do calculations, show the current time, or even interact with other magical beings (databases). However, it's essential to know that CGI, while once widely used, is like an old spellbook that has been replaced by more modern magic (web frameworks and technologies). So, while we're learning about it for fun, many wizards now use different, more powerful spells for their web adventures! 🌟

Conclusion: You're a Coding Wizard! 🌟Congratulations!

Top comments (0)