Saturday 25 October 2014

Java web server demo.

Java HTTP web server demo. Actually a HTTP web server is nothing but a TCP socket connection where first return content must be "HTTP/1.0" with content type and then contents (Html type) or specified. And At last connection must close so the connection stream must break to client. If it is a traditional TCPServer then no need to terminate the connection, we need connection stream. And there is no need of return first content as "HTTP/1.0 ...". For TCPServer code click here.
Keep it simple with this code.


// --------------WebServer.java

import java.io.*;
import java.net.*;

public class WebServer
{
    
    public static void main(String argv[]) throws Exception
    {
        String clientSentence;
        String capitalizedSentence;
        ServerSocket welcomeSocket = new ServerSocket(8989);
        
        // get self IP address and subnet mask
        InetAddress localHost = Inet4Address.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
        String ipAddress = localHost.getHostAddress();
        String subnetMask = "/"+networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
        System.out.println("My ip range :"+ipAddress + subnetMask);
        
        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            // get client ip address
            System.out.print("\nRequest from:"+connectionSocket.getInetAddress().getHostAddress());
            BufferedReader inFromClient =
            new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("\nRequest received: " + clientSentence);
            
            // http response is require
            capitalizedSentence = "HTTP/1.0 200 OK\r\n";
            // content type must set. here it is html content type
            capitalizedSentence = capitalizedSentence + "Content-Type: text/html\r\n\r\n";
            
            /**
            //// above code is managed if we write as
            String s = "HTTP/1.0 ";
            //you probably have seen these if you have been surfing the web a while
            switch (return_code) {
                case 200:
                    s = s + "200 OK";
                    break;
                case 400:
                    s = s + "400 Bad Request";
                    break;
                case 403:
                    s = s + "403 Forbidden";
                    break;
                case 404:
                    s = s + "404 Not Found";
                    break;
                case 500:
                    s = s + "500 Internal Server Error";
                    break;
                case 501:
                    s = s + "501 Not Implemented";
                    break;
            }
            switch (file_type) {
                    //plenty of types for you to fill in
                case 0:
                    s = s + "Content-Type: text/plain\r\n";
                    break;
                case 1:
                    s = s + "Content-Type: image/jpeg\r\n";
                    break;
                case 2:
                    s = s + "Content-Type: image/gif\r\n";
                case 3:
                    s = s + "Content-Type: application/x-zip-compressed\r\n";
                default:
                    s = s + "Content-Type: text/html\r\n";
                    break;
            }
             // for more detail http://fragments.turtlemeat.com/javawebserver.php
             */
            
            
            
            
            
            //// fileContent must have html file content. this is html web server file : index.html probabely. read file from file system and then read the content and then write to outputStream.
            String fileContent = "<h1>Hello, World! </h1>";
            
            
            outToClient.writeBytes(capitalizedSentence+ fileContent);
            
            
            outToClient.writeBytes("<h3>this is new test 1</h3><h4>this is new test2</h4>");
            outToClient.writeBytes("<h5>this is new test new 3</h5>");
            
            //// connection should close to http request. If it is a stream connection then below code is not require. In case of socket connection like TCPServer then we don't need it.
            outToClient.close();
        }
    }
}

No comments:

Post a Comment