How to Build a Simple Web Server in Java

Building a simple web server in Java involves creating a server socket to listen on a specific port, accepting client requests, and sending responses back to the client. Below is a basic example of building a simple HTTP server in Java.

Example Code

package org.kodejava.net;

import java.io.*;
import java.net.*;

public class SimpleWebServer {
    public static void main(String[] args) {
        int port = 8080; // Port number the server will listen on

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                // Accept incoming client connections
                Socket clientSocket = serverSocket.accept();

                // Create a new thread to handle the request
                new Thread(() -> handleClientRequest(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleClientRequest(Socket clientSocket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

            // Read the HTTP request from the client
            String requestLine = in.readLine();
            System.out.println("Client request: " + requestLine);

            // Read and discard the rest of the request headers
            while (in.ready() && in.readLine() != null);

            // Build a basic HTTP response
            String responseBody = "<html><body><h1>Welcome to Simple Java Web Server</h1></body></html>";
            String response = "HTTP/1.1 200 OK\r\n" +
                              "Content-Type: text/html\r\n" +
                              "Content-Length: " + responseBody.length() + "\r\n" +
                              "\r\n" +
                              responseBody;

            // Send the HTTP response to the client
            out.write(response);
            out.flush();

        } catch (IOException e) {
            System.err.println("Client handling exception: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("Failed to close client socket: " + e.getMessage());
            }
        }
    }
}

Steps to Run the Server

  1. Compile the Code
    Save the file as SimpleWebServer.java and compile it:

    javac SimpleWebServer.java
    
  2. Run the Server
    Execute the program:

    java SimpleWebServer
    
  3. Access the Server
    Open a web browser and navigate to http://localhost:808. You should see the message:
    Welcome to Simple Java Web Server.

Key Concepts

  1. ServerSocket:
    The ServerSocket class is used to listen on a specific port for incoming connections.
  2. Socket:
    Represents the client’s connection. You can use the Socket object to read the request and send the response.
  3. HTTP Protocol:
    The server follows a basic structure of HTTP responses:

    • First the status line (e.g., HTTP/1.1 200 OK).
    • Then the headers (e.g., Content-Type and Content-Length).
    • Finally, the response body.
  4. Multithreading:
    Each client connection is handled on a separate thread to allow the server to process multiple requests simultaneously.

Notes

  • Error Handling: Additional error handling should be implemented in production-level servers.
  • Performance: For larger servers, consider using established frameworks like Spring Boot or Jakarta EE.
  • Security: This is a basic example and does not address security concerns like HTTPS, request validation, etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.