Saturday, August 21, 2010

A simple socket program using Java

A simple socket program using Java
The socket connection has two major parts, the code that executes at client-side and the code that executes at server-side. So using the functionality of sockets can be partitioned into two major steps:
  1. The server or the server-side code
  2. The client or the client-side code
Server:
/*Server side program*/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer 
{
    public static void main(String[] args) throws Exception
    {
        ServerSocket server=new ServerSocket(8);
        while(true)
        {
             System.out.println("Waiting for client Request.....");
             Socket socket=server.accept();
             System.out.println("Client : "+new ObjectInputStream(socket.getInputStream()).readObject());
             new ObjectOutputStream(socket.getOutputStream()).writeObject("hi welcome");
        }
    }
}

In the above program ServerSocket server=new ServerSocket(8),
server is a server side socket.
The server listening the client request through port number 8.
One point to keep in mind is that the above mentioned constructors return TCP sockets and not UDP sockets.
Socket socket;  is used communicate with client.
server.accept() method is return the socket, which is connected to server.
ObjectInputStream() is used to get the message from client through connected Socket.
ObjectOutputStream() is used to send the message to client through connected Socket.

Client:
/* Client program*/
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class SimpleClient 
{
    public static void main(String[] args) throws Exception
    {
        Socket socket=new Socket(InetAddress.getLocalHost(),8);
        new ObjectOutputStream(socket.getOutputStream()).writeObject("Hi how r u");
        System.out.println("From Server : "+new ObjectInputStream(socket.getInputStream()).readObject());
    }
}

Here socket is an object used to connect with Server. The constructor socket(InetAddress.getLocalHost(),8) has tow arguments ,
  1. InetAddress.getLocalHost() is the address of server,here the server and client program are running on a single host, so the method getLocalHost() is called.
  2. 8 is the port number of server,which is listening.
ObjectOutputStream() is used to send the message to server through connected Socket.
ObjectInputStream() is used to get the message from server through connected Socket.

Copy and paste the above two programs and save as SimpleServer.java and SimpleClient.java respectively.
Compile it, and run the two programs in different command prompt window.

Wednesday, August 18, 2010

Analog Clock using Java

Analog clock using Applet

Here i am going to show how to design an analog using java program. The main concept of analog clock is drawing the hands of the clock. The analog clock has three hands(hour,minute and second),these are drawing by lines. The drawline() method  has four arguments,they are starting and ending coordinates respectively.

If g is object of Graphics,then

g.drawLine(x1,y1,x2,y2);
x1,y1-starting point
x2,y2-ending point

Here  i draw the line form center point of the clock. So x1 and y1 are center points. The end point of the hand are calculated by some trigonometric calculations.

Screen Shot:


Program:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
/*<applet code=MyClock height=500 width=500></applet>*/
public class MyClock extends Applet implements Runnable
{
         /* sx and sy are end point of second hand and lsx and lsy are previous hand 
             used to hide the pervious drew line */
        int sx,sy,lsx,lsy;               
        int mx,my,lmx,lmy;          
        int hx,hy,lhx,lhy;
        int sr,mr,hr,center;

        int px1,py1,px2,py2;


        double dhs,dhm,dhh;          /*size of hands using in sin and cos functions to measure end point of hand*/
        Random rndm;                   /*random value used to change the clock color*/
        Thread t;
        Font clockFaceFont;

        int s,h,m;

        boolean off=false,dfirst=true; /*off used to stop the thread and dfirst draw the number only at first time*/
        Dimension dm;
        Color wallcolor,bgcolor=Color.black;
        int prvsm,prvss;
        public MyClock()
        {
               
                addMouseListener(new MouseAdapter()
                {
                        int change;
                        public void mouseEntered(MouseEvent me)
                        {
                                dm=size();
                               
                                if(change!=dm.height)
                                {
                                        center=dm.height/2;
                                        setSize(new Dimension(dm.height,dm.height));
                                }
                                else
                                {
                                        center=dm.width/2;
                                        setSize(new Dimension(dm.width,dm.width));
                                }
                                dfirst=true;
                                change=dm.height;     
                                sr=(int)(0.7*center);  /*measure the hand size with respect to windowsize*/
                                mr=(int)(0.75*center);
                                hr=(int)(0.5*center);
                               
                        }
                });
                       
        }
        public void init()  throws NullPointerException
        {

                rndm=new Random();
                t=new Thread(this);
                dm=size();
                center=dm.height/2;

                sr=(int)(0.7*center);   //second hand size
                mr=(int)(0.75*center);
                hr=(int)(0.5*center);
                wallcolor=new Color(rndm.nextInt(255),rndm.nextInt(255),rndm.nextInt(255));//set wallcolor
                t.start();
        }
        public void run() throws NullPointerException
        {
                while(true)
                {
                        s=new Date().getSeconds();  //get time for system

                        if(s!=prvss)
                        {

                                dhs=Math.toRadians(s*6-90);
                                sx=(int)(sr*Math.cos(dhs))+center;
                                sy=(int)(sr*Math.sin(dhs))+center;
       
                                px1=(int)((sr+center*0.15)*Math.cos(dhs))+center;
                                py1=(int)((sr+center*0.15)*Math.sin(dhs))+center;
       

                                m=new Date().getMinutes();
                                dhm=Math.toRadians(m*6-90);
                                mx=(int)(mr*Math.cos(dhm))+center;
                                my=(int)(mr*Math.sin(dhm))+center;
       
                                px2=(int)((sr+center*0.15)*Math.cos(dhm))+center;
                                py2=(int)((sr+center*0.15)*Math.sin(dhm))+center;


                                h =new Date().getHours();
                                dhh=Math.toRadians(h*30-90+((m-1)/2));
                                hx=(int)(hr*Math.cos(dhh))+center;
                                hy=(int)(hr*Math.sin(dhh))+center;

                                repaint();
                                prvss=s;
                        }

                        try
                        {
                                Thread.sleep(100);
                                if(off)
                                        break;

                        }catch(InterruptedException e){}

                                       
                }
        }
        public void update(Graphics g) throws NullPointerException
        {

                if(dfirst==true)
                {
                       
                        clockFaceFont=new Font("Serif",Font.PLAIN,(int)(0.2*center));
                        dfirst=false;
                }
                if(m!=prvsm)
                if(s==0)
                {
                       
                        wallcolor=new Color(rndm.nextInt(255),rndm.nextInt(255),rndm.nextInt(255));
                        g.setColor(wallcolor);
                        g.fillOval(0,0,2*center,2*center);
                        g.setColor(bgcolor);
                        g.fillOval((int)(0.1*center),(int)(0.1*center),(int)(center*1.8),(int)(center*1.8));
                       
                        clear(g);
                        prvsm=m;
                }

                drawPoints(g);//drawing points on clock

                g.setColor(Color.white);
                g.setFont(clockFaceFont);
                //drawing the clock numbers at some point from center
                g.drawString("12",(int)(0.9*center),(int)(0.25*center));
                g.drawString("6",(int)(0.95*center),(int)(1.885*center));
                g.drawString("9",(int)(0.11*center),(int)(1.06*center));
                g.drawString("3",(int)(1.805*center),(int)(1.07*center));
                g.drawString("1",(int)(1.369*center),(int)(0.36*center));
                g.drawString("2",(int)(1.674*center),(int)(0.645*center));
                g.drawString("4",(int)(1.665*center),(int)(1.485*center));
                g.drawString("5",(int)(1.372*center),(int)(1.778*center));
                g.drawString("7",(int)(0.545*center),(int)(1.777*center));
                g.drawString("8",(int)(0.227*center),(int)(1.485*center));
                g.drawString("10",(int)(0.212*center),(int)(0.675*center));
                g.drawString("11",(int)(0.522*center),(int)(0.365*center));
                       
            
                if(lsx!=0)
                {
                        g.setColor(bgcolor);
                        g.drawLine(center,center,lsx,lsy);

                }

                //show the hour hand with biggest size
                g.setColor(Color.green);
                g.drawLine(center,center,hx,hy);
                g.drawLine(center+1,center,hx,hy);
                g.drawLine(center-1,center,hx,hy);
                g.drawLine(center,center+1,hx,hy);
                g.drawLine(center,center-1,hx,hy);
                g.drawLine(center+2,center,hx,hy);
                g.drawLine(center-2,center,hx,hy);
                g.drawLine(center,center+2,hx,hy);
                g.drawLine(center,center-2,hx,hy);
              
                //show the minute hand with bigger size
                g.setColor(Color.blue);
                g.drawLine(center,center,mx,my);
                g.drawLine(center+1,center,mx,my);
                g.drawLine(center-1,center,mx,my);
                g.drawLine(center,center+1,mx,my);
                g.drawLine(center,center-1,mx,my);

                g.setColor(Color.red);
                g.drawLine(center,center,sx,sy);
                g.fillOval(center-3,center-3,6,6);       //center point

                if(m%5!=0)
                {
                        g.setColor(Color.cyan);
                        g.fillOval(px2-2,py2-2,4,4);

                }

                if(s%5!=0)
                {
                        g.setColor(Color.red);
                        g.fillOval(px1-2,py1-2,4,4);

                }

                lmx=mx;
                lmy=my;
                lhx=hx;
                lhy=hy;
                lsx=sx;
                lsy=sy;

                                                           
               
        }
        public void paint(Graphics g)  throws NullPointerException
        {

                g.setColor(wallcolor);
                g.fillOval(0,0,2*center,2*center);
                g.setColor(bgcolor);
                g.fillOval((int)(0.1*center),(int)(0.1*center),(int)(center*1.8),(int)(center*1.8));

        }
        public void clear(Graphics g)  throws NullPointerException
        {
                if(lsx!=0)
                {
                        g.setColor(bgcolor);
                        g.drawLine(center,center,lhx,lhy);
                        g.drawLine(center+1,center,lhx,lhy);
                        g.drawLine(center-1,center,lhx,lhy);
                        g.drawLine(center,center+1,lhx,lhy);
                        g.drawLine(center,center-1,lhx,lhy);
                        g.drawLine(center+2,center,lhx,lhy);
                        g.drawLine(center-2,center,lhx,lhy);
                        g.drawLine(center,center+2,lhx,lhy);
                        g.drawLine(center,center-2,lhx,lhy);
                       
                        g.drawLine(center,center,lmx,lmy);
                        g.drawLine(center+1,center,lmx,lmy);
                        g.drawLine(center-1,center,lmx,lmy);
                        g.drawLine(center,center+1,lmx,lmy);
                        g.drawLine(center,center-1,lmx,lmy);


                }

               
        }
        public void drawPoints(Graphics g) throws NullPointerException
        {
                        int x1,y1;
                        double p;
                        for(int i=1;i<=60;i++)
                        {
                                if(i%5!=0)
                                {
                                        p=i*0.10472;
                                        x1=(int)((sr+center*0.15)*Math.cos(p))+center;
                                        y1=(int)((sr+center*0.15)*Math.sin(p))+center;
                                        g.setColor(Color.gray);
                                        g.fillOval(x1-2,y1-2,4,4);
                                                                   
                                }
                        }

               
        }
        public void stop() throws NullPointerException /*close the thread when applet stopped*/
        {
                off=true;
                t=null;
        }
}

Copy and the paste the above program in notepad and save as "MyClock.java".
Compile the program in command : C:\jdk\bin\javac MyClock.java
Run the Program :C:\jdk\bin\appletviewer MyClock.java
This is a big program,if any doubt email me , i solve your doubt.

My Email Id: sreethephoenix@gmail.com.