Saturday, February 27, 2016

Study of Socket Programming and Client – Server mode

AIM:

To implement socket programming date and time display from client to server using TCP Sockets

ALGORITHM:

Server

  1. Create a server socket and bind it to port.

  1. Listen for new connection and when a connection arrives, accept it.

  1. Send servers date and time to the client.

  1. Read clients IP address sent by the client.

  1. Display the client details.

  1. Repeat steps 2-5 until the server is terminated.

  1. Close all streams.

  1. Close the server socket.

    1. Stop.

Client

  1. Create a client socket and connect it to the servers port number.

  1. Retrieve its own IP address using built-in function.

  1. Send its address to the server.

    1. Display the date & time sent by the server.

    1. Close the input and output streams.

    1. Close the client socket.

7. Stop.


PROGRAM:
DateClient.java:
import java.net.*;
import java.io.*;
class dateclient
{
public static void main (String args[])
{
Socket soc;
DataInputStream dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia=InetAddress.getLocalHost();
soc=new Socket(ia,8020);
dis=new DataInputStream(soc.getInputStream());
sdate=dis.readLine();
System.out.println("THE date in the server is:"+sdate);
ps=new PrintStream(soc.getOutputStream());
ps.println(ia);
}
catch(IOException e)
{
System.out.println("THE EXCEPTION is :"+e);

}
}
}


DateServer.java:
import java.net.*;
import java.io.*;
import java.util.*;
class dateserver
{
public static void main(String args[])
{
ServerSocket ss;
Socket s;
PrintStream ps;
DataInputStream dis;
String inet;
try
{
ss=new ServerSocket(8020);
while(true)
{
s=ss.accept();
ps=new PrintStream(s.getOutputStream());
Date d=new Date();
ps.println(d);
dis=new DataInputStream(s.getInputStream());
inet=dis.readLine();
System.out.println("THE CLIENT SYSTEM ADDRESS IS :"+inet);
ps.close();
}
}
catch(IOException e)
{
System.out.println("The exception is :"+e);
}
}
}

OUTPUT:
CLIENTSIDE:
C:\Program Files\Java\jdk1.5.0\bin>javac dateclient.java
Note: dateclient.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java dateclient
THE date in the server is:Sat Mar 19 13:01:16 GMT+05:30 2008
C:\Program Files\Java\jdk1.5.0\bin>

SERVERSIDE:
C:\Program Files\Java\jdk1.5.0\bin>javac dateserver.java
Note: dateserver.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java dateserver

THE CLIENT SYSTEM ADDRESS IS :com17/192.168.21.17

No comments:

Post a Comment