Before diving in the programming first we have to understand how TCP protocol works -
- 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.
- Establish Connection between source and destination.
- Sends data over a Physical medium and wait for Acknowledgment from destination.
- If data packets lost (Acknowledgment not received in specified time) in between the data is resent.
- on receiving end data is arranged in sequence using header sequence of segment.
- 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 :-
- establish connection b/w Sender and receiver so they can talk to each other.
- send message .
- display message.
- 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
- import java.io.*;
- import java.net.*;
- public class MyServer {
- public static void main(String[] args){
- try{
- ServerSocket ss=new ServerSocket(6666);
- Socket s=ss.accept();//establishes connection
- DataInputStream dis=new DataInputStream(s.getInputStream());
- String str=(String)dis.readUTF();
- System.out.println("message= "+str);
- ss.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
- //MyClient.java
- import java.io.*;
- import java.net.*;
- public class MyClient {
- public static void main(String[] args) {
- try{
- Socket s=new Socket("localhost",6666);
- DataOutputStream dout=new DataOutputStream(s.getOutputStream());
- dout.writeUTF("Hello Server");
- dout.flush();
- dout.close();
- s.close();
- }catch(Exception e){System.out.println(e);}
- }
- }
How to Run:-
To execute this program open two command prompts and execute each program at each command prompt
Next :- VERY basic chat app
Next :- VERY basic chat app
No comments:
Post a Comment