Chandra Sekhar Nayak
Chandra Sekhar Nayak

Reputation: 41

java socket programming

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.

Upvotes: 0

Views: 224

Answers (3)

yoozer8
yoozer8

Reputation: 7489

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.

Upvotes: 1

Michał Šrajer
Michał Šrajer

Reputation: 31182

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 2

Related Questions