Thursday 17 December 2015

Creating your own http server using python script.


This lesson is about creating your own web server without using apache. To do this we are using two libraries.
BaseHTTPServer and SimpleHTTPServer.  BaseHTTPServer creates the http daemon and SimpleHTTPServer
creates the http handler. The program takes one argument which is the port number to which server will be running.
If no port number is mentioned server will run on port 8000.







So here is the code for your Web Server.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

Handler = SimpleHTTPRequestHandler
Server = BaseHTTPServer.HTTPServer

Protocol = "HTTP/1.1"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000

server_address = ("127.0.0.1", port)
# if you are opt to use this on your local machine 127.0.0.1, but you want to use it as web server in a network
# with various sub net then use 0.0.0.0 instead.

Handler.protocol_version = Protocol
httpd = Server(server_address, Handler)
print("HTTP Server started...")
httpd.serve_forever()

After saving this files (i.e. PythonWebServer.py), goto the command line and type
python PythonWebServer.py 8000 (8000 port number is optional.)

The directory where you executed PythonWebServer.py is the root directory of your web server.
Create a html file on the root, named say firstPage.html

Now open your browser and type localhost:8000/firstPage.html
And your html page will be parsed and displayed.

This type of web server can be used on your local desktop or small home network.

Sunday 13 December 2015

Executing python script from Web Browser without using Apache.


 In one of our last blog we have demonstrated that how to execute python script on web browser using Apache Web
Server. In this tutorial we will you how to execute python script in browser without using apache web server.. Python has one of it's own library CGIHTTPServer.py which creates a web server capable of performing as web server. For creating this web server all you need is python application version 2.7. 
Download link of python 2.7
1. For 32bit version 
2. For 64 bit version.

After downloading and installing, goto the python root directory.(i.e. c:\python27)
You have to run this command here.

C:\Python27>python -m CGIHTTPServer 

When you run this command it will start the server at default port 8000.
If you want to run it in a different port just add a port number after the command given above

C:\Python27>python -m CGIHTTPServer 9000

Now check whether you have a folder named cgi-bin on the python root directory.If not create one
using md or mkdir cgi-bin and changed to cgi-bin directory.
Put all your executable python script on this folder.

Now go to the browser and type localhost:9000/cgi-bin/sample.py

Though the server will run by typing localhost:9000 but python code will  only parsed by browser when executing script from cgi-bin folder.

Example sample.py
#D!\Python27\python

print "Content-type: text/html\n"


print "<html><head><title>Hello CGI</title></head>"

print "<body><h2>Hello from CGIHTTPServer<h2>r</body></html>"

Executing this script will show

Hello from CGIHTTPServer

Tuesday 8 December 2015

Server Client socket programming in Java

This tutorial is made with a purpose of understanding the basic concepts of socket programming with Java. For socket programming you need a package java.net which is within J2SE API's, which consists of classes and interface for low level communications. java.net supports communication with 2 types of protocols,
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). In this tutorial we are dealing with to application, one Server and another Client. When the Server program starts it listens for client request on the host address given and on a given port number. Ports already in use cannot be used, server is also set to a timeout after 10 seconds. Then the client program which whenever connects to the server, server accepts connection and sends a reply to the client.

1. SocketServer.java.

/*Import these 2 packages, first one is for socket programming and the second one is for input output streaming. */
import java.net.*;
import java.io.*;

public class SocketServer extends Thread
{
   private ServerSocket serverSocket;

   public SocketServer(int port) throws IOException
   {
     
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);    
    }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "....");
                Socket server = serverSocket.accept();
                System.out.println("Connected to " + server.getRemoteSocketAddress());
                DataInputStream in  = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thanks for connecting to " + server.getLocalSocketAddress());
                server.close();          
            }
            catch(SocketTimeoutException s)
            {
                System.out.println("\nSocket time out..");
                break;
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
                break;
            }
        }
    }

    public static void main(String[] args)
    {
        int port = Integer.parseInt(args[0]);
        try
        {
            Thread t = new SocketServer(port);
            t.start();          
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

2. SocketClient.java

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

public class SocketClient
{
    public static void main(String[] args)
    {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try
        {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, port);
            //client.connect();
            System.out.println("Connected to " + client.getRemoteSocketAddress());
            OutputStream outServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outServer);
            out.writeUTF("\nHello from " + client.getLocalSocketAddress());
            InputStream inServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inServer);
            System.out.println("Server says..." + in.readUTF());
            client.close();           
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}