I am trying to write a simple http server in java. And here's my code so far:
Server:
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Server
{
static final int PORT = 8080;
final String REQUEST_FORMAT = "^GET (.*?) HTTP/1.1$";
final Socket client;
public Server(Socket s)
{
client = s;
}
public void run()
{
try
(Scanner in = new Scanner(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(),true);)
{
String request = in.findInLine(Pattern.compile(REQUEST_FORMAT));
System.out.println(request);
out.write("HTTP/1.1 200 OK");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String []args)
{
try
(
ServerSocket server = new ServerSocket(PORT);
Socket client = server.accept();
)
{
Server s = new Server(client);
s.run();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Client:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
final int PORT = 8080;
String data = "GET /home/index.html HTTP/1.1";
public Client()
{
try
(Socket socket = new Socket("127.0.0.1",PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
Scanner in = new Scanner(new InputStreamReader(socket.getInputStream()));)
{
out.print(data);
String header1 = in.next();
System.out.println("header="+header1);
int status = in.nextInt();
System.out.println("status="+status);
String message = in.next();
System.out.println("message="+message);
}
catch(Exception ex)
{
}
}
public static void main(String []args)
{
Client c = new Client();
}
}
Currently the client just writes a sample request to the server and the server writes a sample response header. But the server seems to be waiting infinitely for client input after reading the request without proceeding to send the response. Please help to resolve this problem.