Listening to Http requests ona a server
hii all
My task needs to create a serversocket and listen on a specified port.
I want to listen only to http requests in the sense my buisness logic deals only with http requests and i donot want other things.(something like a http server).How do i achieve this on my server?How will i know the request that has come to the server is a HTTP request?
Can anyone tell me how to go about it?
Thanx in advance
You need to read up on the RFCs for HTTP and Java network programming.
The first line of text that an HTTP client or proxy will send to a server is the request for a resource and follows something like this:
GET /index.htm HTTP/1.1
Now, any good program and almost all commercial applications will fllow the rules of the WKP (Well Known Ports), these are ports used by long-existing, well-known, or standardized programs/services.
Port 80, 8080, and 443 are used for HTTP, HTTP through proxy, and Secure HTTP (in that order).
Any client connecting to any of these ports SHOULD be looking for a Web server. Thus, their first message SHOULD be similar to what I printed above.
Next, making an HTTP Server (the hand-coded/old-fashion way):
import java.net.*;
import java.io.*;
public class MyHttpServer {
public void main(String args[]) {
try {
ServerSocket server = new ServerSocket(80);
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
String message = in.readLine();
if (message.startsWith("GET ")) {
// client is making an HTTP request
} else
if (message.startsWith("GET ")) {
// client might not be looking for an HTTP server, valid messages would be 'GET','POST','HEAD', and a few others though not typically used.
}
in.close();
out.close();
socket.close();
server.close();
} catch(IOException e) {
e.printStacktrace();
}
}
}