Wednesday, March 14, 2012

Java Program -1 way Client-Server Communication using TCP/IP



In java Networking is done using Sockets and ServerSockets.To get a good idea of how sockets are used in java for creating a client server model see the article. http://c-madeeasy.blogspot.com/2012/03/concept-of-sockets-and-networking-in.html

TCP/IP(Transmission Control Protocol/Internet Protocol) :
Is connection based protocol that is widely used over the internet.It is commonly referred to as IP.The following program uses TCP/IP to communicate.


After reading the above article,see the code below.You can see how socket and server sockets are used to create a one way client server program.Here a client can communicate with the server only.Both are DOS/Terminal Java Programs.

Fist you start the server program followed by client program in two separate terminals.In the client terminal type anything,you can see that appearing in the server terminal window.

The complete Java Program source code to implement 1 way client and server model is provided below as two separate programs Client.java and Server.Java

 //Server Program  
 //c-madeeasy.blogspot.com www.codeuniverse.tk  
 import java.io.*;  
 import java.net.*;  
 class server{  
 public static void main(String []args)  
 {  
 String data;  
 ServerSocket ssock;  
 Socket clientsock=null;  
  DataInputStream is;  
 try{  
 ssock=new ServerSocket(2000);  
 System.out.print("Server Started");  
 clientsock=ssock.accept();  
 is=new DataInputStream(clientsock.getInputStream());  
 System.out.println("Connection Accepted");  
 while(true)  
 {  
 data=is.readLine();  
 System.out.println(data);  
 }  
 }  
 catch(Exception e)  
 {  
 System.out.println("ERROR");  
 }  
 }  
 }  
 ---------------------------------------------------------------  
 //Client Program  
 import java.io.*;  
 import java.net.*;  
 class client{  
 public static void main(String []args)  
 {  
 String text;  
 Socket sock=null;  
  DataOutputStream dout;  
  PrintStream sender;  
  DataInputStream keyboardreader;  
  System.out.println("Connecting to Server.....");  
  try{  
   sock=new Socket("localhost",2000);  
   }  
  catch(Exception e)  
  {  
  }  
  try{  
  System.out.println("Connected");  
  keyboardreader=new DataInputStream(System.in);  
  sender=new PrintStream(sock.getOutputStream());  
  do  
  {  
  text=keyboardreader.readLine();  
  sender.println(text);  
  }while(!text.equals("quit"));  

No comments:

Post a Comment

Which is the Best Photo Watermarking Software

Photo Theft is becoming more and more common in the web with the outburst of social websites like Facebook,Google Plus and Image sharing se...