Issue
I need to program a small server to handle requests from an Android application. (The user sends a number to the server, the server does some math on the numbers received from each user - the average, let's say - and returns it).
I've just read this simple introduction from Oracle (http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html).
It explains how to leave a server listening on a specific door. Normal java, no special application needed (such as Tomcat).
I know people generally use 'servlets' (with Tomcat) to accomplish this kind of thing. Why is that? What are the advantages? Can't i just program a sample server like the one described in that simple tutorial, and leave it always running on a computer?
Solution
Using a socket is very simple. At first.
You create your server class, you have it bind to a port and away you go.
The first hurdle you will hit, covered in the comments, is multi-threading. But a simple producer/consumer pattern will solve that for you in no time.
The next problem you will hit is protocol.
Who talks first?
How do you respond?
How do you deal with an invalid request?
What happens if the stream collapses during a request?
Do you open a new socket for each request or does a client hold onto a socket and write multiple requests?
- Maybe you want some sort of non-blocking IO?
This is where HTTP comes in, it is a protocol for communicating over TCP/IP (actually over anything, you could use bits of paper and a bike). It defines answers to all the above questions (and many more).
So, you run a webserver (tomcat, glassfish) and it deals with the raw sockets and sending the right information.
A servlet is an abstraction, when Tomcat has a connection and it has negotiated compression, encryption etc it will pass a request onto the servlet.
The servlet doesn't have to worry about the raw socket, it reads the request and writes a response.
It's worth pointing out that HTTP isn't the only protocol, it's just the one happens to be used for web-browsing. And so the one used by web-servers.
Answered By - Boris the Spider