https://github.com/tejmagar/java-web-server
Example code to make your own Java Web Server which prints Hello World
https://github.com/tejmagar/java-web-server
http java webserver
Last synced: 7 months ago
JSON representation
Example code to make your own Java Web Server which prints Hello World
- Host: GitHub
- URL: https://github.com/tejmagar/java-web-server
- Owner: tejmagar
- Created: 2024-02-21T02:57:14.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-02-21T02:59:23.000Z (almost 2 years ago)
- Last Synced: 2025-01-30T08:43:04.643Z (about 1 year ago)
- Topics: http, java, webserver
- Language: Java
- Homepage:
- Size: 2.93 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Java web server example
Example code to make your own Java Web Server which prints Hello World
```java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("Server is running at http://127.0.0.1:3000");
ServerSocket serverSocket = new ServerSocket(3000);
while (true) {
// Wait for the new connection and block the further execution.
Socket socket = serverSocket.accept();
// Great, browser is connected to our web server
// Print writer is used to write buffered string text. It will not write to the socket until it's buffer is filled.
// Writing to socket at once is faster than writing in very small chunks.
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
// Http Header starts
// Http version and status code for the browser to handle response
printWriter.write("HTTP/1.1 200 OK\r\n");
// We are saying browser, this is a html file
printWriter.write("Content-Type: text/html\r\n");
// Http header ends with \r\n
printWriter.write("\r\n");
// We now write actual response
printWriter.write("
Hello World
");
// If buffered is filled, probably response is already sent. If it's waiting for the buffer to filled,
// we need to flush it to make sure all the data is sent to the browser.
printWriter.flush();
// Closing socket is the simplest way to say to the browser that all data has been sent.
socket.close();
}
}
}
```