0

I've got the following problem:

I'm trying to write a simple webserver in Java, which can host HTML-Files and handle the POST things of formulars in the .html File.

The problem is that the BufferedReader doesn't read the message from the formular in the HTML-Document before I flush the Output Stream.

So I always have to flush the Output Stream before I can handle the POST-Message.

For my server, I need to handle the POST-Message before I'm flushing the Output-Stream, so I can customize the HTML File in the case something happened with the POST message.

Here's my Code (simplized it a bit ;)) of the server:

 import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class NewWebServer {

    public static void main(String[] args) throws Exception {
        new NewWebServer();
    }

    public NewWebServer() {
        waitForConnection();
    }

    /**
     * Open the server
     */
    public void waitForConnection() {
        // Set standard socketPort and serverSocket variable
        ServerSocket serverSocket = null;
        int socketPort = 8080;
        boolean socketFound = false;

        // Search for available socket ports (bigger than 8079)
        while (!socketFound) {
            System.out.println("Try to open Server at Port " + socketPort);

            try {
                // Try to open server socket
                serverSocket = new ServerSocket(socketPort);

                // Server Socket openend
                socketFound = true;
            } catch (Exception e) {
                e.printStackTrace();

                // Set port + 1
                socketPort++;
            }

            System.out.println("++++++++++++++++Server Openened++++++++++");
            System.out.println("Server started at Port " + socketPort);
        }

        Socket socket;
        for (;;) {
            try {
                System.out.println("Server waiting for Connection");
                socket = serverSocket.accept();
                System.out.println("Server got Connection");
                new Thread(new SocketHandler(socket)).start();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    class SocketHandler implements Runnable {
        Socket socket;

        public SocketHandler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            // Handle the Input Stream
            new Thread(new InputStreamHandler(socket)).start();
        }
    }

    class InputStreamHandler implements Runnable {
        Socket socketToHandle;
        DataOutputStream dataOutputStream;

        public InputStreamHandler(Socket socketToHandle) {
            this.socketToHandle = socketToHandle;
        }

        public void run() {
            BufferedReader bufferedReader;

            try {
                // Initialize BufferedReader to read Input Stream
                bufferedReader = new BufferedReader(new InputStreamReader(socketToHandle.getInputStream()));

                // Initialize DataOutputStream to Handle OutputStream
                dataOutputStream = new DataOutputStream(socketToHandle.getOutputStream());

                String lineOfInputStream = null;

                /*
                 * Write the Website Header and the .html file
                 * 
                 * Have to be before the Input Stream reading, if not send , the
                 * post of the HTML Formular can't be read ! ?
                 */
                new Thread(new WriteToOutputStream(dataOutputStream)).start();

                // Read the InputStream
                while ((lineOfInputStream = bufferedReader.readLine()) != null) {
                    System.out.println("InputStream got Line " + lineOfInputStream);
                }

                System.out.println("BufferedReader finished");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class WriteToOutputStream implements Runnable {
        DataOutputStream out;

        public WriteToOutputStream(DataOutputStream dataOutputStream) {
            this.out = dataOutputStream;
        }

        public void run() {
            System.out.println("Run WriteToOutputStream");

            // File of HTML File with <form action="" method="POST"> Formular
            File file = new File("C:/htdocs/test.html");
            FileInputStream fileInputStream;

            try {
                // Open File Input Stream
                fileInputStream = new FileInputStream(file);

                // Write the Header for the Browser , to handle the .html Output
                out.writeBytes("HTTP/1.0 200 OK\r\n");
                out.writeBytes("Content-Type: text/html\r\n");
                out.writeBytes("Content-Length: " + fileInputStream.available() + "\r\n");
                out.writeBytes("Server: Jastonex/0.1");
                out.writeBytes("\r\n\r\n");

                // Initialize Bytes
                byte[] fileBytes = null;

                // Read the file, convert it into a byte array
                fileBytes = new byte[fileInputStream.available()];
                fileInputStream.read(fileBytes);

                // Write the byte array of the file into the output stream
                out.write(fileBytes);

                // Flush
                out.flush();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("OutputStreamRun finished");
        }

    }
}

Here's an example of a HTML File I'm hosting:

<html>
	<head>
		<title>ASDF</title>
	</head>
	<body>
		<p style="color:red;">Blablabla</p>
		<form action="" method="POST">
		<input type="password" name="passwort" value="Bla"/>
		<input type="password2" name="passwort2" value="Bla"/>
		<input type="password3" name="passwort34" value="Bla"/>
		<input type="password4" name="passwort55" value="Bla"/>
			<input type="submit" name="submit" value="Testbutton">
		</form>
	</body>
</html>

And here's the output in the console:

Try to open Server at Port 8080
++++++++++++++++Server Openened++++++++++
Server started at Port 8080
Server waiting for Connection
Server got Connection
Server waiting for Connection
Run WriteToOutputStream
InputStream got Line POST /asshjshshs HTTP/1.1
InputStream got Line Host: localhost:8080
InputStream got Line Connection: keep-alive
InputStream got Line Content-Length: 74
InputStream got Line Cache-Control: max-age=0
InputStream got Line Origin: http://localhost:8080
InputStream got Line Upgrade-Insecure-Requests: 1
InputStream got Line User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
InputStream got Line Content-Type: application/x-www-form-urlencoded
InputStream got Line Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
InputStream got Line Referer: http://localhost:8080/asshjshshs
InputStream got Line Accept-Encoding: gzip, deflate, br
InputStream got Line Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
InputStream got Line 
OutputStreamRun finished
InputStream got Line passwort=Bla&passwort2=Bla&passwort34=Bla&passwort55=Bla&submit=Testbutton
BufferedReader finished

The line I need before flushing the OutputDataStream is the following:

passwort=Bla&passwort2=Bla&passwort34=Bla&passwort55=Bla&submit=Testbutton

The executing browser is the chrome browser, but the internet explorer generates the Input Stream the same way -.-

Hope you can help me ;)

1 Answer 1

0

Okay - I just found out that this is the workflow after pressing the button in the HTML-Formular:

  1. Get Connection , Sending Message to Server with the POST Action, get Return Message, close Socket

  2. Get New Connection, Sending a clean Message to the Server without the Post Message, get Return Message , show it as HTML Code.

Is there an unique way to identificate the client to assign the second message to the first?

If I can assign them , I can generate the HTML-Output in the second message by converting the Form-Data of the first message.

Edit: Only if Port is over than 8080 and only works in Chrome

Can somebody help me ? :D

1
  • But thats just in the Browser Chrome, in the internet explorer and edge-Browser I always get 1 call of the website.
    – Arol
    Commented Nov 9, 2016 at 11:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.