/* Implementation of Socket Programming Using TCP */
// TCPServer.java : A Simple TCP Server Program
import java.net.*;
import java.util.*;
import java.io.*;
public class TCPServer
{
public static void main(String args[]) throws IOException
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket ss = new ServerSocket(Port);
System.out.println(" Wait Client Socket is Connecting ..... ");
Socket s=ss.accept();
if(s.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
OutputStream out = s.getOutputStream();
PrintWriter p=new PrintWriter(out);
Date d=new Date();
p.print(" Current Server Time is : " + d);
p.flush();
out.close();
System.out.println(" Message send Successfully. " );
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
// TCPClient.java : A simple TCP Client Program
import java.net.*;
import java.io.*;
public class TCPClient
{
public static void main(String args[]) throws IOException
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
Socket s = new Socket("localhost",Port);
if(s.isConnected()==true)
System.out.println(" Server Socket is Connected Succecfully. ");
InputStream in = s.getInputStream();
BufferedReader buf=new BufferedReader(new
InputStreamReader(in));
String str = buf.readLine();
System.out.println(" Message Received From Server. " );
System.out.println(str);
in.close();
s.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
OUTPUT :
TCPServer.java :
javac TCPServer.java
java TCPServer
Enter the Port Address : 1234
Wait Client Socket is Connecting .....
Client Socket is Connected Succecfully.
Message send Successfully.
TCPClient.java :
javac TCPClient.java
java TCPClient
Enter the Port Address : 1234
Server Socket is Connected Succecfully.
Message Received From Server.
Current Server Time is : Thu Sep 02 19:37:48 IST 2010
No comments:
Post a Comment