TCP - Udp Example Programs PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Course Content

1. Network Terms
2. IP address, Port Numbers
3. Socket : TCP and UDP
4. Process
5. HTTP and HTTPS
6. Peer to Peer
7. FTP, Email, SMTP, MIME, PGP, ICMP
8. Unicast, Broadcast, Multicast
9. Client Side and Server Side Technologies
10. Firewall and Proxy
11. CORBA, J2EE, .NET
12. RIP, OSPF, BGP – Protocols
13. RTP, RTCP, RTSP Protocols
14. IP Overview
15. Router Architecture
16. MPLS, Control Plane, SIP, IP, Multicast, Packet Forwading, PBR
Lab Programs

1. Find IP
2. IP and MAC
3. Ports
4. Socket : UDP and TCP
5. Process
6. Thread
7. MultiThread
8. Thread: Extends, Runnable
9. Thread States
10. HTTP
11. HTTP Server
12. Peer to Peer Server
13. Broadcast
14. Multicast
15. RIP Protocol (Packet Tracer)
• Communication: UDP: Datagram, TCP: Stream

• UDP is connectionless protocol: Always sends the


local socket descriptor and receiving socket's address.

• TCP is connection-oriented protocol: Connection


must first be established between the pair of sockets.

• Data Arrival: TCP: Order, UDP: Random

• Data delivery: Using Ports by TCP & UDP (16 bit)

• Size: UDP: 64 Kb, TCP: No limit

• Reliable: TCP: Yes, UDP: No

Example:

• TCP: Networking services like telnet, FTP,

• UDP: Client Server Apps (LAN)


SOCKET

• Socket: Endpoint of a two way communication link between two programs


running on the network

• Endpoint: Combination of an IP and Port #

• Types: ServerSocket and Socket

• ServerSocket: Used by servers

• Socket: Used by clients; servers use it too for communication with clients

• [Server + PortListener] <--ConnectionRequest<-- [Port + Client]

• [Server + PortListener] ---> ConnectionResponse --> [Port + Client]

• Input stream: Attached to some input source for the process,


Eg., keyboard or socket.

• Output stream: Attached to an output source, e.g., monitor or socket


TCP CLIENT

• In Client, if connection accepted, Socket is created in Client to


communicate with Server.

• Client and Server communicates by their own Sockets.

• TCP connections identified by its two endpoints.


(multiple connections are possible)

• import java.net.*; package provides a class, 'SOCKET',

• 'SOCKET' class hides the details of any system from java

• 'SERVERSOCKET' class used by server to listen & accept


TCP CLIENT: CONNECTION CREATION STEPS

1. Creating a new socket

2. Declaring a message

3. Obtaining streams associated with the socket (OutputStream and ObjectOutputStream)

4. writeObject() to send message

5. Closing streams

6. Closing the socket


1. Create a new socket

Socket Socket_name = new Socket("Machine name", PortNumber);

Eg. Socket skt = new Socket("127.0.0.1", 6999);

• Machine name: Address of the server


• PortNumber: Port Number on the server (0 to 1023 are reserved)
• 127.0.0.1: Default address of the local system in computer networks

2. Declaring a message

String String_name = “Message”;

Eg. String msg = "Hello Server";

• This message is sent to the server from client


3. Obtaining streams associated with the socket
OutputStream OutputStream_name = Socket_name.getOutputStream();

ObjectOutputStream ObjectOutputStream_name = new ObjectOutputStream(OutputStream_name);

Eg. OutputStream os = skt.getOutputStream();


ObjectOutputStream oos = new ObjectOutputStream(os);

• OutputStream is used for creating output stream for socket(skt)


• getOutputStream() method returns an object of OutputStream, here the object is os.
• ObjectOutputStream is used for creating object for output stream

4. writeObject to send message

ObjectOutputStream_name.writeObject(msg);
Eg. oos.writeObject(msg);

• writeObject() takes the string message and passes to the Socket.


5. Closing the Streams

ObjectOutputStream_name.close();
OutputStream_name.close();
Eg. oos.close();
os.close();

• ObjectOutputStream and OutputStreams are to be closed before closing Socket.

6. Closing the Socket

Socket_name.close();

Eg. skt.close();

• Finally, Socket should be closed to close the connection


Example: MyClient.java
// importing java packages
import java.io.*;
import java.net.*;

public class MyClient {


public static void main(String args[]) {
try
{
// create a new socket for communicating with the server
Socket skt = new Socket("127.0.0.1", 6999);
System.out.println("Connected to server");

// declaring a message
String msg = "Hello Server";

//creating output stream for socket(skt)


OutputStream os = skt.getOutputStream();

//creating object for output stream


ObjectOutputStream oos = new ObjectOutputStream(os);
Example: MyClient.java

// send a message to server using writeobject


oos.writeObject(msg);
System.out.println("Sent a message to server");

// close object output stream


oos.close();
os.close();
skt.close();
}

catch(Exception e)
{ System.out.println(e);
}} }
TCP SERVER: CONNECTION CREATION STEPS

1. Creating a new Server Socket

2. Accepting a connection from Client on Server

3. Creating Streams (InputStream and ObjectInputStream)

4. Reading message (readObject)

5. Closing Streams

6. Closing the Socket (Server and Client)


1. Creating a new Server Socket
• Server does Jobs (2):
1. To communicate (by using Socket.)
2. To Bind the connection on Port number. (by using ServerSocket)

• Binding is nothing but dedicating the port number to the client as long as it would like;

ServerSocket ServerSocket_name = new ServerSocket(PortNumber);

Eg. ServerSocket ss = new ServerSocket(6999);

2. Accepting a connection from Client on Server

Socket Socket_name == ServerSocket_name.accept();

Eg. Socket skt = ss.accept();

• accept() is used to bind the connection on the port number, requested by the client. .
3. Creating Streams (InputStream and ObjectInputStream)

• getInputStream() method of Socket returns an object of InputStream and this is the starting point on the server
program.
• The server uses input stream as it is receiving the message.

• InputStream InputStream_name = Socket_name.getInputStream();


Eg. InputStream is = skt.

•As InputStream is an abstract class, it cannot be used directly. It is chained to a concrete class ObjectInputStream.

ObjectInputStream ObjectInputStream_name = new ObjectInputStream(InputStream_name);


Eg. ObjectInputStream ois = new ObjectInputStream(is);

4. Reading message (readObject)

•readObject() method of ObjectInputStream reads the message string from the socket and
returns. This message is printed at the console.

Datatype Variable_name = (Datatype)ObjectInputStream_name.readObject();


Eg. String msg = (String)ois.readObject();
5. Closing Streams

The ObjectInputStream and InputStream are closed

System.out.println("Server recieved message : " + msg);


System.out.println("Server is exiting ... ");
ois.close();
is.close();

6. Closing the Socket (Server and Client)

Finally, Client Socket and ServerSocket are closed.

Eg. skt.close();
ss.close();
Example: MyServer.java
//import packages
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args)
{ try {
// Create a new server socket that listens at port 6999
ServerSocket ss = new ServerSocket(6999);
System.out.println("Server is lisenting ... ");

//wait for connection from client on port 6999


Socket skt = ss.accept();

//InputStream for getting input from client


InputStream is = skt.getInputStream();

//declare Object for InputStream


ObjectInputStream ois = new ObjectInputStream(is);

// recieve message from client


String msg = (String)ois.readObject();
Example: MyServer.java

// display the output


System.out.println("Server recieved message : " + msg);
System.out.println("Server is exiting ... ");

/* close open streams and socket */


ois.close();
is.close();
skt.close();
ss.close();
}

catch(Exception e)
{ System.out.println(e);
}
}}
DatagramSocket and DatagramPacket

• UDP Sockets in Java: DatagramSocket and DatagramPacket

• These classes are used for connection-less socket programming.


DatagramSocket

• It is a connection-less socket for sending and receiving datagram packets.


• No guarantee of its content, arrival or arrival time.

CONSTRUCTORS: DatagramSocket

• DatagramSocket()

– Creates a socket and chooses the list of available port numbers

• DatagramSocket(int port)

– Creates a Socket and binds with a specified port numbers

• DatagramSocket(int port, InetAddress address)

– Creates a Socket with given port number and IP address

METHODS

– getData() : Returns the data contained in this packet as a byte array.

– getLength() : Returns the length of the data to send or receive


DatagramPacket

• It is a message that can be sent or received.

• If you send multiple packet, it may arrive in any order.

• Packet delivery is not guaranteed.

CONSTRUCTORS: DatagramPacket
• DatagramPacket(byte[] barr, int length)
– it creates a datagram packet to receive the packets.

• DatagramPacket(byte[] barr, int length, InetAddress address, int port)


– it creates a datagram packet to send the packets.
Example: UDP RECEIVER
import java.net.*;
public class Receiver{
public static void main(String[] args) throws Exception
{
// Datagram Socket for Port no. 3000
DatagramSocket ds = new DatagramSocket(3000);

// Defining size of Packet


byte[] buf = new byte[1024];

// Creating Datagram Packet


DatagramPacket dp = new DatagramPacket(buf, 1024);

// receive Datagram Packet


ds.receive(dp);

// getData() is used to Return the data contained in this packet as a byte array.
String str = new String(dp.getData(), 0, dp.getLength());

System.out.println("Receiver is Waiting for the message:");


System.out.println("Message received : " +str);

// close the datagram Socket


ds.close();
Example: UDP SENDER

import java.net.*;
public class Sender
{
public static void main(String[] args) throws Exception
{
// Creating DatagramSocket
DatagramSocket ds = new DatagramSocket();

String str = "Welcome to Network Programming";

// Defining IP address
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


System.out.println("Sender is sending the message :");

// Send data packet and close connection


ds.send(dp);
ds.close();
}
}
1001101001010110
0000101110001110
0000110111001100
----------------------------
1011001110110000 (+) ------- 0100110001001111 CHECKSUM
----------------------------

1001101001010110 +
0000101110001110 +
0000110111001100 +
0100110001001111 =
---------------------------- if there is one 0, then that means errors
1111111111111111

You might also like