Link to home
Start Free TrialLog in
Avatar of -eck-
-eck-

asked on

Problems with simple Java Based HTTP-SocketServer

Greetings everybody,

I'm trying to build a simple HTTP-SocketServer in Java. The very basic idea of the program is to listen for HTTP-Requests, stream-in the Request, and send back a HTTP-Response.

The Code:


package httpconnection;

import java.io.*;
import java.net.*;

public class Main {
   
    /** Creates a new instance of Main */
    public Main() {
    }
   
    public static void main(String[] args) {
        try
        {
            ServerSocket lServerSocket = new ServerSocket( 9999, 0, InetAddress.getByName( "127.0.0.1" ) );
            Socket lSocket = lServerSocket.accept();

            InputStream lInputStream = lSocket.getInputStream();
            BufferedReader lBufferedReader = new BufferedReader( new InputStreamReader( lInputStream ) );

            String lStrHTTPrequest = "";
            int lIntCharacterReadFromRequest;
            String lStrHTTPrequestHeaderLine = "";
            String lStrAllHTTPrequestHeaders = "";
           
            while ( ( lIntCharacterReadFromRequest = lBufferedReader.read() ) != -1 )
            {
                System.out.print( ( char )lIntCharacterReadFromRequest );
            }
           
            String lStrResponse = "HTTP/1.1 302 Found\n" +
                    "Content-Type: text/html\n" +
                    "Server: GlobalCHatServer 0.01 alpha\n" +
                    "Transfer-Encoding: chunked\n" +
                    "Content-Type: text/html\n" +
                    "\n" +
                    "<HTML><HEAD></HEAD><BODY>an evil petting zoo?</BODY></HTML>";
           
            OutputStream lOutputStream = lSocket.getOutputStream();
            lOutputStream.write(lStrResponse.getBytes());
            lSocket.close();
            lSocket = null;
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
}

The Code itself compiled perfectly, and was able to cath and print out the HTTP-Request. For some reason, the program was halted at the while-loop, and no response is sent back to the client. There is also no Error-Message is printed out in the console.

Should we put the response lines output before the while-loop, clients could perfectly recieve the wanted response-header.

and I can't figure out why the program halted in the while loop, Any suggestions please?

Thanks a lot in advance,

-eck-
Avatar of Mick Barry
Mick Barry
Flag of Australia image

>             while ( ( lIntCharacterReadFromRequest = lBufferedReader.read() ) != -1 )

this will block until the streamm is closed.
and it won't get closed until you send the response.

SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Once you get a connection in accept (), you should ideally let another thread handle that client:

https://www.experts-exchange.com/questions/21757720/Is-there-any-sample-online-for-socket-and-multi-thread.html#16084277
Avatar of Webstorm
Webstorm

Hi -eck-,

>> ServerSocket lServerSocket = new ServerSocket( 9999, 0, InetAddress.getByName( "127.0.0.1" ) );
you may need backlog > 0 :
ServerSocket lServerSocket = new ServerSocket( 9999, 50, InetAddress.getByName( "127.0.0.1" ) );

and loop to answer multiple requests:

for(;;)
{
    Socket lSocket = lServerSocket.accept();
    try{
    ...
    } catch(IOException ioex){}
    finally { lSocket.close(); }
}
You also need to use \r\n instead of \n, and specify content-length (HTTP 1.1) :

           String lStrResponse = "HTTP/1.1 302 Found\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Server: GlobalCHatServer 0.01 alpha\r\n" +
                    "Connection: close\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: 59\r\n" +
                    "\r\n" +
                    "<HTML><HEAD></HEAD><BODY>an evil petting zoo?</BODY></HTML>";
and :
    lOutputStream.flush(); // just before closing the socket
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of -eck-

ASKER

Hi all,

thanks a lot for the reat replies, I'm trying to replace the old while loop with this argument:

while ((lStrLineReadFromRequest = lBufferedReader.readLine())!="End_Of_Request_String" )
           {
               System.out.println( lStrLineReadFromRequest );
           }

Of course, I've replaced all the local variables to meet up the need, the problem is, I don't know, what we should use in place of "End_Of_Request_String", I've tried "\r" "\n" "\r\n" "null" and all of them don't work, any suggestions?

Also, thanks a lot for the "\r\n" tip :-)

-eck-
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of -eck-

ASKER

Wow, okay, problem solved. Thanks a lot again guys for the help :-)

-eck-
no worries :)
>> Also, thanks a lot for the "\r\n" tip :-)
but no points ...