Program No.
07: Using TCP/IP sockets, write a client – server program to make the client send the file
name and to make the server send back the contents of the requested file if present.
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The [Link] package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.
The [Link] package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to
as TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.
Sockets are a protocol independent method of creating a connection between processes. Sockets
can be either
➢ Connection based or connectionless: Is a connection established
before communication or does each packet describe the destination?
➢ Packet based or streams based: Are there message boundaries or is it one stream?
➢ Reliable or unreliable: Can messages be lost, duplicated, reordered, or corrupted?
Socket characteristics
Sockets are characterized by their domain, type and transport protocol. Common
domains are:
➢ AF_UNIX: address format is UNIX pathname
➢ AF_INET: address format is host and port number Common types are:
➢ virtual circuit: received in order transmitted and reliably
➢ datagram: arbitrary order, unreliable Each socket type has one or more
protocols. Ex:
➢ TCP/IP (virtual circuits)
➢ UDP(datagram)
Use of sockets:
➢ Connection–based sockets communicate client-server: the server waits for a
connection from the client
➢ Connectionless sockets are peer-to-peer: each process is symmetric.
Socket is an interface which enables the client and the server to communicate and
pass on information from one another. Sockets provide the communication mechanism
between two computers using TCP. A client program creates a socket on its end of the
communication and attempts to connect that socket to a server. When the connection is
made, the server creates a socket object on its end of the communication. The client and
the server can now communicate by writing to and reading from the socket. The
[Link] class represents a socket, and the [Link] Socket class provides
a mechanism for the server program to listen for clients and establish connections with
them.
Fig. 1 The client-server application using TCP
As shown in the Fig. 1, the following steps occur when establishing a TCP connection
between two computers using sockets –
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
• The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server
and the port number. If communication is established, the client now has a Socket object
capable of communicating with the server.
• On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.
Steps:
➢ BufferedReader Object, keyRead is created to take input from the keyboard
➢ To send the file name to the server, PrintWriter is used
➢ To receive the file contents from t e server, SocketReader of bufferedReader is created.
➢ PrintWriter is got a provision for auto flushing
➢ Second parameter of the constructor is set to true to indicate auto flushing.
Applications:
Sockets allow you to exchange information between processes on the same machine or
across a network, distribute work to the most efficient machine, and they easily allow
access to centralized data. Socket application program interfaces (APIs) are the network
standard for TCP/IP. A wide range of operating systems support socket APIs. i5/OS
sockets support multiple transport and networking protocols. Socket system functions
and the socket network functions are thread safe. Two or more process can communicate
using sockets. This is majorly used in operating system. If one process needs some
information from other. It just creates a socket, and it will get the details accordingly.
We can transfer file or message form one computer to another computer. We can create
any sever, client applications. Like FTP,HTTP,DNS etc
Algorithm (Client Side)
➢ Start.
➢ Create a socket using socket() system call.
➢ Connect the socket to the address of the server using connect() system call.
➢ Send the filename of required file using send() system call
➢ Read the contents of the file sent by server by recv() system call.
➢ Stop.
Algorithm (Server Side)
➢ Start.
➢ Create a socket using socket() system call.
➢ Bind the socket to an address using bind() system call.
➢ Listen to the connection using listen() system call.
➢ accept connection using accept()
➢ Receive filename and transfer contents of file with client.
➢ Stop.
Program:
Client Side
Program:
Import [Link].*; import [Link].*;
public class FileClient
{
public static void main(String[] args)
{
new FileClient();
}
public FileClient()
{
BufferedReaderbufReader=new BufferedReader(new InputStreamReader([Link])); try
{
[Link]("Enter IP address of the server:"); String
saddr = [Link]();
Socket clientsocket=new Socket(saddr,8000);
[Link]("Connecting to Server....");
DataInputStream input=new
DataInputStream([Link]());
DataOutputStream output=new
DataOutputStream([Link]());
[Link]("Enter File Name:");
String Name=[Link]();
[Link](Name);
String EchoedFile=[Link]();
[Link]("-----------------------------------------------");
[Link]("Content of a File:\n\n"+EchoedFile);
[Link]("-----------------------------------------------");
[Link]();
}
catch(IOException ex)
{
[Link]();
}}}
Server-Side Program:
import [Link].*; [Link].*;
public class FileServer
{
public static void main(String[] args)
{
new FileServer();
}
public FileServer()
{
try
{
ServerSocketserversocket=new ServerSocket(8000);
[Link]("Server Started....");
[Link]("-----------------------------------------------");
Socket socket=[Link]();
DataInputStream input=new
DataInputStream([Link]());
DataOutputStream output=new DataOutputStream([Link]());
String str=[Link]();
[Link]("Requested File Name:"+str);
[Link]("-----------------------------------------------");
try
{
InputStream in = new FileInputStream(str);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
[Link]("Reading Contents of the File...");
[Link]("-----------------------------------------------");
while ((line = [Link]()) != null) {
[Link](line+"\n");
}
String everything= [Link]();
[Link]("File Contents sent to client...");
[Link]("-----------------------------------------------");
}
catch(Exception ex)
{
everything="File Not Found!";
}
[Link](everything);
}
catch(Exception ex)
{
[Link]();
}
}
}
Note: Create two different files [Link] and [Link]. Follow the steps given:
1. Open a terminal run the server program and provide the filename to send.
2. Open one more terminal run the client program and provide the IP address of the server.
We can give local host address “[Link]” as it is running on same machine or give the
IP address of the machine.
Program No. 08: Write a program on datagram socket for client/server to display the messages
on client side, typed at the server side.
A datagram socket is the one for sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently and may arrive in any order.
Datagram packets are used to implement a connectionless packet delivery service supported by
the UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination
address and each packet might be routed differently and might arrive in any order. Packet delivery
is not guaranteed.
Java supports datagram communication through the following classes:
➢ DatagramPacket
➢ DatagramSocket
UDP client/server communication flow:
Applications:
Sockets allow you to exchange information between processes on the same machine or across a
network, distribute work to the most efficient machine, and they easily allow access to centralized
data. Socket application program interfaces (APIs) are the network standard for TCP/IP. A wide
range of operating systems support socket APIs. i5/OS sockets support multiple transport and
networking protocols. Socket system functions and the socket network functions are thread safe.
Two or more process can communicate using sockets. This is majorly used in operating system.
If one process needs some information from other. It just creates a socket, and it will get the details
accordingly. We can transfer file or message form one computer to another computer. We can
create any sever, client applications. Like FTP,HTTP,DNS etc
Algorithm:
UDP Server :
1. Create UDP socket.
2. Bind the socket to server address.
3. Wait until datagram packet arrives from client.
4. Process the datagram packet and send a reply to client.
5. Go back to Step 3
UDP Client :
1. Create UDP socket.
2. Send message to server.
3. Wait until response from server is received.
4. Process reply and go back to step 2, if necessary.
5. Close socket descriptor and exit.
Program:
Client Side Program:
import [Link].*; import [Link].*; class
UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the IP address of the Server:");
String saddr = [Link]();
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = [Link](saddr);
byte[] receiveData;
byte[] sendData = new byte[200];
String sentence = "Hello";
sendData = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], IPAddress, 9876);
[Link](sendPacket);
while(true)
{
receiveData = new byte[200];
DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);
[Link](receivePacket);
String incomingData = new String([Link]());
InetAddress SAddress = [Link]();
[Link]("FROM SERVER"+"("+[Link]()+"): " + incomingData);
[Link]("------------------------------------------------------------");
}
}
}
Server Side Program:
import [Link].*; import [Link].*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
[Link]("--------Server Started-------");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader([Link]));
byte[] receiveData = new byte[200];
byte[] sendData;
DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);
[Link](receivePacket);
InetAddress clientAddress = [Link]();
int port = [Link]();
[Link]("Client with IP Address "+[Link]()+" connected...");
[Link]("------------------------------------------------------------");
[Link]("Enter the message to send to client:");
while(true)
{
String input =
[Link]();
sendData = new byte[200];
sendData = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
clientAddress, port);
[Link](sendPacket);
}
}
}
Note: Create two different files [Link] and [Link].
Follow the following steps:
1. Open a terminal run the server program.
2. Open one more terminal run the client program, the sent message will be received.