Q. Write a Java program to fetch date and time from server to client by using TCP Socket.
Ans.
Server side program (input):
import java.net.*;
import java.io.*;
import java.util.*;
class server
{
public static void main (String args[])
{
ServerSocket ss=null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{
ss=new ServerSocket(4444);
System.out.println ("Press Ctrl+c to Quit");
while(true)
{
cs=ss.accept();
ps=new PrintStream(cs.getOutputStream());
Date d=new Date();
ps.println(d);
dis=new BufferedReader(new InputStreamReader(cs.getInputStream()));
inet=dis.readLine();
System.out.println ("Client System/IP address is :" +inet);
ps.close();
dis.close();
}
}
catch (IOException e)
{
System.out.println("The exception is:" +e);
}
}
}
Client side program:
import java.net.*;
import java.io.*;
class client
{
public static void main(String args[])
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia= InetAddress.getLocalHost();
if(args.length==0)
soc= new Socket(InetAddress.getLocalHost(),4444);
else
soc= new Socket(InetAddress.getByName(args[0]),4444);
dis= new BufferedReader(new InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("The date/time on server is :"+sdate);
ps= new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
}
catch (IOException e)
{
System.out.println("The exception is:" +e);
}
}
}
Output:
Server side:
javac server.java (//enter)
java server (//enter)
Press Ctrl+c to Quit.
Client System/IP address is : MyComputer/192.168.0.8
Client Side:
javac clinet.java (//enter)
java client (//enter)
The date/time on server is : Thu Feb 07 10:29:07 IST 2019
Free image Downloaded from unsplash.com |
0 Comments