Java Program to Setup Simple HTTP server

12 August, 2022

2

2

0

Java has very good networking support it allows you to write client-server applications by using TCP sockets below are the Java code snippets to create simple HTTP server in Java
Steps to create HTTP server We need to create network socket that can accept connections on certain TCP ports. You can use "ServerSocket" class in java to create Server which accept requests
Now it's time to write code to accept connections. Java allows us accept connections by blocking call to "accept()" method. This is a blocking method and blocks until a client connects to the server. As soon as a client connect it returns the Socket object which can be used to read client request and send response to client. Once you are done with a client you should close this socket and get ready to accept the new incoming connection by calling accept() again.
This is the standard HTTP Server, its simple because HTTP is stateless, which means it doesn't need to remember the previous connection, all it cares for new incoming connections. This is an endless cycle until the server is stopped. Now let's see what is coming from the browser in form of the HTTP request. When you connect to http://localhost:8080,your browser will send a GET HTTP request to the server.
You can read the content of the request using InputStream opened from the client socket. It's better to use BufferedReader because the browser will send multiple lines.
Our HTTP client (Any browser) passes this text to our HTTP server written in Java. You can see that the request type is GET and the protocol used here is HTTP/1.1. So now our server is not only listening for connection, but accepting it and also reading HTTP request. Now the only thing remaining is to send an HTTP response back to the client. To keep our server simple, we will just send today's date to the client. In order to send a response, we need to get the output stream from the socket, and then we will write HTTP response code OK and today's date into the stream.
If you get todays date on browser, It means HTTP sever is working properly. The only limitation of this server is that it can serve one client at a time.
That's all about how to create an HTTP server in Java. This is a good example to learn network programming in Java.

2

2

0

AlokHangari
Got me thinking

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.