0

Can I write a socket programming to provide services to the web clients? I did it using servlet, but I want to do it using java.net API. Please give me a sample code of some program, such that I can access that simply by mentioning URL at the address bar of any web browser.

2
  • 3
    "Please give me a sample code of some program"...Umm, no? What have you done thus far? Commented Aug 4, 2011 at 18:41
  • homework? as other said, why re-inventing the wheel. Commented Aug 4, 2011 at 19:37

3 Answers 3

2

I suggest you look at the source for jetty. It is the simplest web server I can think of. If you want an ultra basic web server, you can do this with plain sockets, however the HTTP protocol is quite complex and using a web server library to handle all the details is likely to be the best approach.

Sign up to request clarification or add additional context in comments.

1 Comment

Conceptually its relatively simple, but HTTP has a lot of details to worry about and why do it when there and many implementations already available. At the very least you should read and understand what an existing implementation does. AFAIK, all the web server libraries support NIO now. (the link is 7 years old)
1

If you want to be able to receive requests typed into a web browser, you need to do a couple things.

-Set the socket to listen on port 80 -Receive/parse/process HTML requests -Return an HTML response across the socket

Rather than write the code for you, here is some pseudocode

//setup socket on port 80
socket.lisen();
while(true)
{
    newsocket = socket.accept();
    new thread(process(newsocket));
}

The most complicated part, I think, will be handling the HTML, processing the request, and generating a response. After that, just send it back over the socket.

Considering how many libraries are out there for this sort of thing, I wouldn't reccommend writing one from scratch.

Comments

0

The problem is that "web client" is just a browser, so you don't have direct access to TCP/IP. Few options:

  1. HTML5 WebSockets (only modern browsers)
  2. flash helper (there are javascript wrappers)
  3. java applet helper (there are javascript wrappers)
  4. some tricks based on ajax pooling

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.