DEV Community

Anirudh Bukka
Anirudh Bukka

Posted on

Single Threaded Web Server - Responding with 200

This post is to describe how bind to a port and respond with 200.

Binding

First listen to TCP connections at an address and a port. Consider binding as associating server code with a specific IP address and a port number on your machine.
In this example, the server is local, so address is going to be localhost or 127.0.0.1. I set the port as 4221.
ServerSocket serverSocket = new ServerSocket(4221);
This implies that the Java program is now bound to port 4221.

Listening

Listening refers to the server telling the OS that it is ready to accept incoming TCP connections on the port it just bound to.
This implies that when a client connects, the server accepts it via:
Socket clientSocket = serverSocket.accept();

Consider this analogy:

  • Port 4221 is like door #4221.
  • Binding: the server (your java program) sets a receptionist at that door.
  • Listening: that receptionist waits for visitors (client)
  • A client knocks
  • The receptionist opens the door via .accept(), and they talk.

Get 200 Response

So, once a client connects, we have a TCP connection - clientSocket represents that.

Object to read request from the socket.

  • The data sent by client is to be read by the server. And this data is in bytes format (the actual TCP data from the client). var inputStream = clientSocket.getInputStream();
  • Now, convert the bytes from above into characters using character encoding such as UTF-8. InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  • But this still gives only access to read character by character, not lines yet. To read full line of text: BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

Object to write response to the socket.

  • The server now has to send bytes (response) to the client. Since it's in bytes format, it is not human readable. To translate it to human-readable text, PrintWriter wraps the response. PrintWriter printWriter = new PrintWriter(clientSocket.getOutputStream());

Note: this does not print on the terminal, this is sending an HTTP response over the network back to the client.

Now you might ask - what is the point of writing this human readable text back to the client? Simple, that's how HTTP protocol works - it is a text-based protocol and expects structured, text-based responses so that it can understand what our server is saying.

Reading from the socket and writing to the socket

Finally we read from the socket and write to the socket:

// reading from the socket:
requestMessage = bufferedReader.readLine();
System.out.println(requestMessage);

// writing to the socket:
responseMessage = "HTTP/1.1 200 OK\\r\\n\\r\\n";
printWriter.print(System.out.println("Modified message sent to the client: " + responseMessage);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)