Friday, September 23, 2011

Java Socket DayTime Service

DayTimeServer.java

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DayTimeServer
{

    ServerSocket serverSocket;
    Socket clientSocket;
    DataOutputStream dos;


    public DayTimeServer()
    {
        try
        {
            serverSocket = new ServerSocket(13);
            while(true)
            {
                System.out.print("Time Server Start....");
                clientSocket=serverSocket.accept();
                dos=new DataOutputStream(clientSocket.getOutputStream());
                Date date=new Date();
                dos.writeUTF(date.toString());
            }
           
        }
        catch (IOException ex)
        {
            Logger.getLogger(DayTimeServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeServer();
    }
}

DayTimeClient.java

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DayTimeClient
{
    Socket dtSocket;
    DataInputStream dis;

    public DayTimeClient()
    {
        try
        {
           
            dtSocket = new Socket("localhost", 13);
            dis=new DataInputStream(dtSocket.getInputStream());
            System.out.print("-: Day And Time :-\n"+dis.readUTF()+"\n");
        }
        catch (UnknownHostException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeClient();
    }
}

How To Run :
Fisrst Start DayTimeServer.java
Second Start DayTimeClient.java

No comments:

Post a Comment