3

I need to put something like this in my browser:

  http://localhost:1234/page.html

and then obtain the content of "page.html" file. The point is - I got a connection to the 1234 host using Sockets but how on earth should I read the name of the file and pass it to my Socket in order to read different html pages?

Any kind of help would be very appreciated.

zerken
  • 31
  • 1
  • 4
  • 1
    You can make your life a lot easier than just using the built-in http server implementation at com.sun.httpserver. – pvg Dec 13 '15 at 06:56

2 Answers2

1

You should read the socket's content and parse it as a HTTP response.

Take a look at this question. When you parsed the response, you would have access to the headers of the response which includes the URL (path) of the file, then you can read the file and send the content back to the socket. Of course you need to wrap the result in form of an HTTP response as well.

The better option is to use a ready to use web server to do the work. Like tomcat.

Community
  • 1
  • 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • Oh yes, it's true. I've already done this and I have now: "GET /page.html HTTP/1.1 (...)" but I still have no idea how to pick out this url - is there a method for this? (I've read the oracle documentation for Socket and still don't know :( ) – zerken Dec 13 '15 at 00:33
  • I would suggest that you use a ready to use parser to parse the content of the packet. I still dont know at which part you have problems. – Aᴍɪʀ Dec 13 '15 at 00:38
  • Sorry, I spent a lot of time trying to make it work so I stopped thinking logically. My dead point is getting the header with the path to my file and then I don't know how to pass it to my BufferedReader in order to have the content. I'd like to make it in this way if it's possible – zerken Dec 13 '15 at 00:46
  • you can provide some code in your question, people can help you better if you do so. – Aᴍɪʀ Dec 13 '15 at 00:49
0

You will create a standard TCP listener socket and configure it accordingly.

When a browser attempts to navigate to the IP address and port, the browser sends a HTTP 1.1 GET request. Your java program must interpret the request string and respond accordingly. Your response must contain a properly formatted HTTP 1.1 response followed immediately with the HTML.

EDIT: In your comments above, in the GET request you see the / is the path of the file you wish to locate. For example, by default the browser sends just a / so you should respond with the contents of index.htm file because index.htm should be the index right? So code it that way!

If it is a requirement (lol) you will make the TCP socket on a finite number of threads (so you should create a custom class for this) so multiple browsers can access your server at the same time.

Happy coding

Here is a link to help you figure out HTTP requests

user207421
  • 305,947
  • 44
  • 307
  • 483
Jake Psimos
  • 640
  • 3
  • 10