Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printwriter not writing to outputStream

Tags:

java

I'm trying to implement a basic web server in Java. When I direct a web browser to 127.0.0.1:8020/webpage.html, the server receives the request header, but when it tries to send the webpage back it doesn't show up on the browser.

Can anyone help?

public class WebServer
{
    public static void main(String[] args)
    {

        try
        {
            ExecutorService scheduler = Executors.newCachedThreadPool();
            ServerSocket server = new ServerSocket(8020);
            while (true)
            {
                Socket client = server.accept();
                Runnable r = new HTTPThread(client.getInputStream(), client.getOutputStream());
                scheduler.execute(r);      
                System.out.println("LOG: New Thread Created");
            }
        }
        catch (IOException e)
        {
            System.out.println("ERROR: Cannot listen on socket");
            e.printStackTrace(); 
        }
    }
}


public class HTTPThread implements Runnable {
    InputStream in;
    OutputStream out;

    private String fileName;
    private String fileLoc;
    private static final String rootLoc = "C:\\Users\\myName\\workspace\\HTTPServer\\src\\";

    HTTPThread(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public void run() {
        try {

            // show request headers and store http header
            System.out.println("LOG: Preparing to read request");
            String header = readInput(in);
            System.out.println("LOG: Request read successfully!");
            System.out.println(header);


            // get file name from request header
            fileLoc = rootLoc + header.substring(5, header.indexOf("H") - 1);
            System.out.println(fileLoc);


            PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));

            //send response header and body
            writer.print("HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + fileReader(fileLoc));
            System.out.println("LOG: Response Sent");

            out.close();
            in.close();         
        }

        catch (IOException e) {
            System.out.println("ERROR: Could not listen on socket");
            System.exit(-1);
        }

    }

    //Returns content of webpage as a string (html)
    public String fileReader(String file) {

        StringBuilder text = new StringBuilder();
        String NL = System.getProperty("line.separator");
        Scanner scanner;
        try {
            scanner = new Scanner(new FileInputStream(file));
            while (scanner.hasNextLine()) {
                text.append(scanner.nextLine() + NL);
            }

            return text.toString();
        } catch (FileNotFoundException e) {
            System.out.println("ERROR: File Not Found");
            System.exit(-1);
            return null;
        }
    }

    //Reads bytestream from client and returns a string
    private String readInput(InputStream is) {

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        try 
        {
            String current;
            String header = "";
            while (!(current = in.readLine()).isEmpty())
            {
                header += current + System.getProperty("line.separator");       
            }

            return header;
        }
        catch (IOException e) 
        {
            e.printStackTrace();
            return null;
        }
    }
}
like image 870
bananamana Avatar asked May 09 '26 15:05

bananamana


2 Answers

Adding writer.close(); before out.close(); would fix it.

like image 139
srkavin Avatar answered May 11 '26 05:05

srkavin


http responses have a very specific format. the protocol is very specific about which characters separate the header from the content. you have the wrong characters.

as a side note, never use PrintWriter on top of a network stream as it hides IOExceptions (in general, avoid PrintWriter).

like image 30
jtahlborn Avatar answered May 11 '26 06:05

jtahlborn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!