Pages

Sunday, 26 January 2014

Client Server (TCP) programming

Before diving in the programming first we have to understand how TCP protocol works -

  1. It take your data, message, etc and break it in In segments and address them by adding destination address, source address etc in the header of the Message.
  2. Establish Connection between source and destination.
  3. Sends data over a Physical medium and wait for Acknowledgment from destination.
  4. If data packets lost (Acknowledgment not received in specified time) in between the data is resent.
  5. on receiving end data is arranged in sequence using header sequence of segment. 
  6. connection is closed.

Few key Terms of Network Programming:-

  • IP Address :- it is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255. It is not your machine actual address (mac address) rather than it is the address your ISP provided to you. They maintain a table to work it out.
  • Port :- There are more than one application running on a machine.so It is a unique address which is used to identify the application which has to receive data, message, etc etc.

Programming Logic :-

  1. establish connection b/w Sender and receiver so they can talk to each other.
  2. send message .
  3. display message.
  4. Stop if connection is closed.

Prequest :-

  • Basic Understanding of programming logic and control structure (if,else,for etc).
  • Basics of java.

Programming :-


  • ServerSocket class is used to  acquire a port for application and getting the TCP connection.  ServerSocket  represents the Receiving end of communication.
  • Socket Represents the Connection and used to get data input output streams


  1. import java.io.*;  
  2. import java.net.*;  
  3.   
  4. public class MyServer {  
  5. public static void main(String[] args){  
  6. try{  
  7. ServerSocket ss=new ServerSocket(6666);  
  8. Socket s=ss.accept();//establishes connection   
  9.   
  10. DataInputStream dis=new DataInputStream(s.getInputStream());  
  11.   
  12. String  str=(String)dis.readUTF();  
  13. System.out.println("message= "+str);  
  14.   
  15. ss.close();  
  16.   
  17. }catch(Exception e){System.out.println(e);}  
  18. }  
  19. }  


  1. //MyClient.java  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5.   
  6. public class MyClient {  
  7. public static void main(String[] args) {  
  8. try{      
  9. Socket s=new Socket("localhost",6666);  
  10.       
  11. DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
  12.   
  13. dout.writeUTF("Hello Server");  
  14. dout.flush();  
  15.   
  16. dout.close();  
  17. s.close();  
  18.   
  19. }catch(Exception e){System.out.println(e);}  
  20. }  
  21. }  

How to Run:-

To execute this program open two command prompts and execute each program at each command prompt 

Next :- VERY basic chat app

No comments:

Post a Comment