Languages
[Edit]
EN

Java - simple single client Fake-HTTP server example (socket server)

10 points
Created by:
evangeline
420

In this short article, we would like to show how using sockets, write a simple single client Fake-HTTP server in Java.

The solution in the article runs a simple Fake-HTTP server that is able to get only one client connection at the same time. The server listens on port 80. Client requests are only printed in the server console, sending back always the same simple web page - this is the reason why we called it Fake-HTTP server.

Server usage steps:

  1. run Fake-HTTP server (the below Java program),
  2. open http://localhost address in the web browser,

    The web browser should send some similar text to the server as request:

    GET / HTTP/1.1
    Host: localhost
    Connection: keep-alive
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9,pl;q=0.8
    
    Where:
    - each line should be separated with \r\n,
    - last empty line means request end.
  3. as response in the web browser we should see:

    The server sends text as a response (it is interpreted by the web browser and displayed as a web page):

    HTTP/1.1 200 OK
    Server: My WWW Server
    Content-Type: text/html
    
    <!DOCTYPE html>
    <html>
    <body>
      My site body...
    </body>
    </html>
    Where each line should be separated by:
    \r\n in the header area,
    \n in the content area (it is recommended).

 

Used source code

Program.java file:

package com.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Program {

    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(80)) { // starting server on port 80
            while (true) {
                try (
                    Socket clientSocket = serverSocket.accept(); // waiting for the web browser connection
                    BufferedReader bufferedReader = createReader(clientSocket);
                    PrintWriter outputWriter = createWriter(clientSocket);
                ) {
                    System.out.println("-----------------------------------------");
                    // reading data from the web browser (receiving as text)
                    while (true) {
                        String line = bufferedReader.readLine();
                        if (line == null || line.isEmpty()) {
                            break;
                        }
                        System.out.println(line);
                    }
                    // writing data to the web browser (sending as text)
                    outputWriter.print(
                        "HTTP/1.1 200 OK\r\n" +
                        "Server: My WWW Server\r\n" +
                        "Content-Type: text/html\r\n" +
                        "\r\n" +
                        "<!DOCTYPE html>\n" +
                        "<html>\n" +
                        "<body>\n" +
                        "  My site body...\n" +
                        "</body>\n" +
                        "</html>"
                    );
                    outputWriter.flush();
                } catch (IOException ex) {
                    System.err.println(ex.getMessage());
                }
            }
//          closeObject(serverSocket);
        }
    }

    private static BufferedReader createReader(Socket clientSocket) throws IOException {
        InputStream inputStream = clientSocket.getInputStream();
        InputStreamReader inputReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        return new BufferedReader(inputReader);
    }

    private static PrintWriter createWriter(Socket clientSocket) throws IOException {
        OutputStream outputStream = clientSocket.getOutputStream();
        return new PrintWriter(outputStream, true, StandardCharsets.UTF_8);
    }

//    private static boolean closeObject(Closeable object) {
//        if (object == null) {
//            return false;
//        }
//        try {
//            object.close();
//            return true;
//        } catch (IOException ex) {
//            return false;
//        }
//    }
}

Example output:

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join