Last active
April 26, 2022 18:31
-
-
Save Ch3shireDev/b26374d7b41cc561c9acfc2f8ab5d669 to your computer and use it in GitHub Desktop.
SimpleHttpServer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.OutputStreamWriter; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
public class SimpleHttpServer { | |
public static void main(String[] args) throws Exception { | |
int port = 80; | |
ServerSocket serverSocket = new ServerSocket(port); | |
System.out.println("Server listening on port: " + port); | |
while (true) { | |
Socket clientSocket = serverSocket.accept(); | |
System.out.println("New connection openned."); | |
InputStream is = clientSocket.getInputStream(); | |
InputStreamReader isr = new InputStreamReader(is); | |
BufferedReader in = new BufferedReader(isr); | |
OutputStream os = clientSocket.getOutputStream(); | |
OutputStreamWriter osw = new OutputStreamWriter(os); | |
BufferedWriter out = new BufferedWriter(osw); | |
String s; | |
int contentLength = 0; | |
while ((s = in.readLine()) != null) { | |
System.out.println(s); | |
if (s.startsWith("Content-Length:")) { | |
contentLength = Integer.parseInt(s.substring(16)); | |
} | |
if (s.isEmpty()) { | |
break; | |
} | |
} | |
char[] buffer = new char[contentLength]; | |
in.read(buffer, 0, contentLength); | |
System.out.println(new String(buffer)); | |
String body = "<p>response</p>"; | |
out.write("HTTP/1.0 200 OK\r\n"); | |
out.write("Content-Type: text/html\r\n"); | |
out.write(String.format("Content-Length: %d\r\n", body.length())); | |
out.write("\r\n"); | |
out.write(body); | |
System.out.println("Connection terminated."); | |
out.close(); | |
in.close(); | |
clientSocket.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment