You are on page 1of 40

Msc I.

T Part I Advanced Computer


Networks

Theory And Terminology

What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is
bound to a specific port number. The server just waits, listening to the socket
for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on
which the server is running and the port number to which the server is
connected. To make a connection request, the client tries to rendezvous with
the server on the server's machine and port.

If everything goes well, the server accepts the connection. Upon


acceptance, the server gets a new socket bound to a different port. It needs
a new socket (and consequently a different port number) so that it can
continue to listen to the original socket for connection requests while tending
to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully


created and the client can use the socket to communicate with the server.
Note that the socket on the client side is not bound to the port number used
to rendezvous with the server. Rather, the client is assigned a port number
local to the machine on which the client is running.
The client and server can now communicate by writing to or reading
from their sockets.
Definition: A socket is one endpoint of a two-way communication link
between two programs running on the network. A socket is bound to a port
number so that the TCP layer can identify the application that data is
destined to be sent.

The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program
and another program on the network. The Socket class sits on top of a
platform-dependent implementation, hiding the details of any particular
system from your Java program. By using the java.net.Socket class instead of
relying on native code, your Java programs can communicate over the
network in a platform-independent fashion.

Additionally, java.net includes the ServerSocket class, which


implements a socket that servers can use to listen for and accept
connections to clients. This lesson shows you how to use the Socket and
ServerSocket classes.

-1-
Msc I.T Part I Advanced Computer
Networks

Making TCP Connections

These classes are related to making normal TCP connections:


 ServerSocket
 Socket
For simple connections between a client and a server, ServerSocket and
Socket are all that you will probably need.
ServerSocket represents the socket on a server that waits and listens for
requests for service from a client. Socket represents the endpoints for
communication between a server and a client. When a server gets a request
for service, it creates a Socket for communication with the client and
continues to listen for other requests on the ServerSocket. The client also
creates a Socket for communication with the server. The sequence is shown
below how client and a server normally make a TCP connection with
ServerSocket and Socket classes:

Once the connection is established, getInputStream() and getOutputSteam()


may be used in communication between the sockets

Syntax:
To open a socket Socket:
Socket MyClient;
Myclient = new Socket(“Machine name”, PortNumber);
When Implementing server you also need to create a socket object from the
ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null;
try {
serviceSocket = Myservice.accpt();
}
catch(IOException e){ System.out.println(e); }

(In the above program we have used exception handling.)


User Datagram Protocol (UDP)

-2-
Msc I.T Part I Advanced Computer
Networks

UDP UDP
client server

internet Host B
Host A

Definition: A datagram is an independent, self-contained message sent


over the network whose arrival, arrival time, and content are not guaranteed.

UDP provides an unreliable packet delivery system built on top of the IP


protocol. As with IP, each packet is an individual, and is handled separately.

Because of this, the amount of data that can be sent in a UDP packet is
limited to the amount that can be contained in a single IP packet. Thus, a
UDP packet can contain at most 65507 bytes (this is the 65535-byte IP
packet size minus the minimum IP header of 20 bytes and minus the 8-byte
UDP header). UDP packets can arrive out of order or not at all. No packet has
any knowledge of the preceding or following packet. The recipient does not
acknowledge packets, so the sender does not know that the transmission
was successful. UDP has no provisions for flow control--packets can be
received faster than they can be used.

We call this type of communication connectionless because the packets


have no relationship to each other and because there is no state maintained.
The destination IP address and port number is encapsulated in each UDP
packet. These two numbers together uniquely identify the recipient and are
used by the underlying operating system to deliver the packet to a specific
process (application). One way to think of UDP is by analogy to
communications via a letter. You write the letter (this is the data you are
sending); put the letter inside an envelope (the UDP packet); address the
envelope (using an IP address and a port number); put your return address
on the envelope (your local IP address and port number); and then you send
the letter. Like a real letter, you have no way of knowing whether a UDP
packet was received. If you send a second letter one day after the first, the
second one may be received before the first. Or, the second one may never
be received.

So why use UDP if it unreliable? Two reasons: speed and overhead. UDP
packets have almost no overhead--you simply send them then forget about
them. And they are fast, since there is no acknowledgement required for

-3-
Msc I.T Part I Advanced Computer
Networks

each packet. Keep in mind the degree of unreliability we are talking about.
For all practical purposes, an Ethernet breaks down if more than about 2
percent of all packets are lost. So, when we say unreliable, the worst-case
loss is very small. UDP is appropriate for the many network services that do
not require guaranteed delivery. An example of this is a network time
service. Consider a time daemon that issues a UDP packet every second so
computers on the LAN can synchronize their clocks. If a packet is lost, it's no
big deal--the next one will be by in another second and will contain all
necessary information to accomplish the task. Another common use of UDP is
in networked, multi-user games, where a player's position is sent
periodically. Again, if one position update is lost, the next one will contain all
the required information. A broad class of applications is built on top of UDP
using streaming protocols.

With streaming protocols, receiving data in real-time is far more


important than guaranteeing delivery. Examples of real-time streaming
protocols are RealAudio and RealVideo which respectively deliver real-time
streaming audio and video over
the Internet. The reason a streaming protocol is desired in these cases is
because if an audio or video packet is lost, it is much better for the client to
see this as noise or "drop-out" in the sound or picture rather than having a
long pause while the client software stops the playback, requests the missing
data from the server.

That would result in a very choppy, bursty playback which most people
find unacceptable, and which would place a heavy demand on the server.

Practical 1

-4-
Msc I.T Part I Advanced Computer
Networks

Aim: Write a client server program that will display the IP address and
the local host address.

Software Required: Java Development Kit 1.5

Description:
java.net provides addressing-related class InetAddress for IP addressing.
Class InetAddress represents an IP address, which is either a 32- or 128-bit
unsigned number used by IP, the lower-level protocol on which protocols like
TCP and UDP are built.

Server Program:
import java.io.*;
import java.net.*;
public class inetServer
{
public static void main(String a[])
{
System.out.println("Starting Server...WAIT....");
try
{
ServerSocket srv = new ServerSocket(5555);
System.out.println("Server Started : " + srv);
Socket clt = srv.accept();
InetAddress cltAddress = clt.getInetAddress();
System.out.println("Client IP : "+ cltAddress.getHostAddress() +
"\tPort no : "+ clt.getPort());
PrintStream ios = new PrintStream(clt.getOutputStream());
ios.println("Server address is : " + srv);
ios.close();
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}

Client Program:
import java.net.*;
import java.io.*;
public class inetClient
{
public static void main(String ss[])
{

-5-
Msc I.T Part I Advanced Computer
Networks

try
{
InetAddress inetaddr = InetAddress.getLocalHost();
Socket sock =new Socket (inetaddr,5555);
System.out.println("Connection Established to Server");
InputStreamReader input = new InputStreamReader
(sock.getInputStream());
BufferedReader buffreader = new BufferedReader(input);
System.out.println(buffreader.readLine());
}
catch(Exception e)
{
System.out.println("Error : " + e.toString());
}
}
}

Output of Server Program:

-6-
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 2

Aim: Write a client server program to implement client server


communication, create a server that will calculate the greater number

-7-
Msc I.T Part I Advanced Computer
Networks

for client using TCP.

Software Required: Java Development Kit 1.5

Description:
On the client side:
Numbers is accepted from the user through “InputStreamReader(System.in)”
which allows to read line of text and sent to server by opening socket client
side and send the numbers to the server through “PrintWriter” and
“OutputStreamWriter”. Output is sent from server and received by client
using “PrintWriter”
On the server side:
First ServerSocket is created and waits client to open the socket that is
“ss.accept()”. The result is sent from client and calculation is done by server.
The output is sent to client side using “pw.println(Number " +n + " is greater
than " +m);”

Server Program:
import java.io.*;
import java.net.*;
class TCPServerGreater
{
public static void main(String arg[])
{
Socket s;
int port=9999,n,m;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for client");
s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(s.getOutputStream())) ;
String str1=br.readLine();
String str2=br.readLine();
n=Integer.parseInt(str1);
m=Integer.parseInt(str2);
System.out.println("First Number recieve from client: " + n);
System.out.println("Second Number receive from client: " + m);
if (n > m)
pw.println("Number " +n + " is greater than " +m);
else
pw.println("Number " +m + " is greater than " +n);
pw.flush();
pw.close(); br.close();
s.close(); ss.close();
}

-8-
Msc I.T Part I Advanced Computer
Networks

catch(Exception e) { }
}
}

Client Program:
import java.io.*;
import java.net.*;
class TCPClientGreater
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
System.out.print("Enter the First Number: ");
String str1=br.readLine();
System.out.print("Enter the Second Number: ");
String str2=br.readLine();
pw.println(str1);
pw.println(str2);
pw.flush();
msg=br1.readLine();
System.out.println("Answer from server : ");
System.out.println(msg);
}
catch(Exception e) { }
}
}
Output of Server Program:

-9-
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 3

Aim: Write a client server program to implement client server


communication, create a server that will calculate the factorial for
client using UDP.

- 10 -
Msc I.T Part I Advanced Computer
Networks

Software Required: Java Development Kit 1.5

Description:
On the client side:
A number is accepted from the user through ‘InputStreamReader(System.in)’
which allows to read line of text and sent to server using ‘ DatagramPacket
outDgp = new DatagramPacket
(numbers.getBytes(),numbers.length(),host,port)’ and ‘client.send(outDgp)’.
Output is sent from server and received by client using ‘ DatagramPacket
inDgp =new DatagramPacket (buffer,buffer.length)’ and
‘client.receive(inDgp)’
On the server side:
A number is sent from client and calculation is done by server. The output is
sent to client side using ‘DatagramPacket outDgp=new DatagramPacket
(rsp.getBytes() ,rsp.length() ,senderAddress ,senderPort)’ and
‘ss.send(outDgp)’

Server Program:
import java.io.*;
import java.net.*;
public class UDPServerFactorial
{
public static void main(String args[])
{
int port =7896;
try
{
DatagramSocket ss=new DatagramSocket(port);
byte[] buffer =new byte[256];
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
String req,rsp;
System.out.println("Waiting for client");
ss.receive(inDgp);
InetAddress senderAddress =inDgp.getAddress();
int senderPort =inDgp.getPort();
req=new String(inDgp.getData(),0,inDgp.getLength());
int fact=1;
int num=Integer.parseInt(req);
System.out.println("Number receive from client: "+num);
for(int i=2;i<=num;i++)
fact=fact*i;
rsp="Factorial of the number is "+ fact;
DatagramPacket outDgp=new
DatagramPacket(rsp.getBytes(),rsp.length(),senderAddress,senderP
ort);
ss.send(outDgp);
ss.close();
}

- 11 -
Msc I.T Part I Advanced Computer
Networks

catch(Exception e) {System.out.println("Exception "+ e);}


}
}

Client Program:
import java.io.*;
import java.net.*;
public class UDPClientFactorial
{
public static void main(String args[])
{
InetAddress host;
int port=7896;
try
{
host = InetAddress.getLocalHost();
DatagramSocket client=new DatagramSocket();
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a Number : ");
String Numbers=br.readLine();
DatagramPacket outDgp =new DatagramPacket
(Numbers.getBytes() ,Numbers.length(),host,port);
client.send(outDgp);
byte buffer[]=new byte[256];
DatagramPacket inDgp =new
DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new
String(inDgp.getData(),0,inDgp.getLength());
System.out.println("Answer from server:");
System.out.println(rsp);
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//End of main
}
Output of Server Program:

- 12 -
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 4

Aim: Create a TCP based echo server.

Software Required: Java Development Kit 1.5

- 13 -
Msc I.T Part I Advanced Computer
Networks

Description:
Basics in this program:
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.

Server Program:
import java.io.*;
import java.net.*;
class TCPServerEcho
{
public static void main(String arg[])
{
Socket s;
int port=9999,count=0;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Echo Server Started... \n Waiting for Client");
s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader
(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter
(s.getOutputStream())) ;
while(true)
{
String str=br.readLine();
if (str.equals("bye")) System.out.println("Client
Terminated");
System.out.println("Message from the Client: "+str);
pw.println(str.toUpperCase());
pw.flush();
}
pw.close();
br.close();
s.close();
ss.close();
}
catch(Exception e) { }
}
}
Client Program:
import java.io.*;
import java.net.*;

class TCPClientEcho

- 14 -
Msc I.T Part I Advanced Computer
Networks

{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
while(true)
{
System.out.print("Message: ");
String str=br.readLine();
pw.println(str);
pw.flush();
if(str.equals("bye")) System.exit(0);
msg=br1.readLine();
System.out.println("Echo: " + msg);
}
br1.close();
pw.close();
osw.close();
s.close();
ss.close();
}
catch(Exception e) { }
}
}

Output of Server Program:

- 15 -
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 5

Aim: Create a UDP based echo server.

Software Required: Java Development Kit 1.5

- 16 -
Msc I.T Part I Advanced Computer
Networks

Server Program:
import java.io.*;
import java.net.*;
public class UDPServerEcho
{
public static void main(String args[])
{
int port =7896;
try
{
DatagramSocket ss=new DatagramSocket(port);
byte[] buffer =new byte[256];
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
String req,rsp;
System.out.println("Waiting for client");
while(true)
{
ss.receive(inDgp);
InetAddress senderAddress =inDgp.getAddress();
int senderPort =inDgp.getPort();
req=new String(inDgp.getData(),0,inDgp.getLength());
if(req.equals("bye"))
System.out.println("Client Terminated");
ss.close();System.exit(0);
System.out.println("Message from Client: " + req);
rsp=req.toUpperCase();
DatagramPacket outDgp=new DatagramPacket (rsp.getBytes()
,rsp.length(), senderAddress ,senderPort);
ss.send(outDgp);
}
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}

Client Program:
import java.io.*;
import java.net.*;

public class UDPClientEcho


{
public static void main(String args[])
{
InetAddress host;
int port=7896;

- 17 -
Msc I.T Part I Advanced Computer
Networks

try
{
host = InetAddress.getLocalHost();
DatagramSocket client=new DatagramSocket();
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
System.out.print("Message: ");
String str1=br.readLine();
DatagramPacket outDgp =new DatagramPacket
(str1.getBytes(), str1.length(), host,port);
client.send(outDgp);
if(str1.equals("bye"))
System.out.println("Client Terminated"); break;
byte buffer[]=new byte[256];
DatagramPacket inDgp =new
DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new String(inDgp.getData(),0,inDgp.getLength());
System.out.println("Echo: " + rsp);
}
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//End of main
}

Output of Server Program:

- 18 -
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 6
Aim: Create an iterative connection-oriented server.

Software Required: Java Development Kit 1.5

- 19 -
Msc I.T Part I Advanced Computer
Networks

Server Program:
import java.io.*;
import java.net.*;

class TCPServerFactorial
{
public static void main(String arg[])
{
Socket s;
int id;
int port=9999,count=0;
try
{
ServerSocket ss=new ServerSocket(port);
System.out.println("Waiting for client");
s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter
(s.getOutputStream())) ;
while(true)
{
String str=br.readLine();
if (str.equals("bye"))
System.out.println("Client Terminated");
int n=Integer.parseInt(str);
int i,f=1;
System.out.println("Number receive from client: " + n);
for(i = 2; i <= n; i++)
f = f * i;
pw.println("Factorial is : "+f);
pw.flush();
}
}
catch(Exception e) { }
}
}
Client Program:
import java.io.*;
import java.net.*;

class TCPClientFactorial
{
public static void main(String arg[])
{
int port=9999;
Socket s;
String msg="";
try

- 20 -
Msc I.T Part I Advanced Computer
Networks

{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress addr=InetAddress.getByName(null);
s=new Socket(addr,port);
OutputStreamWriter osw=new
OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
while(true)
{
System.out.print("Enter a Number (bye to EXIT): ");
String str=br.readLine();
pw.println(str);
pw.flush();
if(str.equals("bye"))
System.exit(0);
msg=br1.readLine();
System.out.println("Answer from server : ");
System.out.println(msg);
}
br1.close();
pw.close();
osw.close();
s.close();
ss.close();
}
catch (Exception e) { }
}
}

Output of Server Program:

- 21 -
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 7

Aim: Create an iterative connection-less server.

Software Required: Java Development Kit 1.5

Server Program:
import java.io.*;
import java.net.*;
import java.lang.*;
public class UDPServerPalindrome
{
public static void main(String args[])
{
int port =7896;
try
{

- 22 -
Msc I.T Part I Advanced Computer
Networks

DatagramSocket ss=new DatagramSocket(port);


byte[] buffer =new byte[256];
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
String req,rsp,rev;
System.out.println("Waiting for client");
while(true)
{
ss.receive(inDgp);
InetAddress senderAddress =inDgp.getAddress();
int senderPort =inDgp.getPort();
req=new String(inDgp.getData(),0,inDgp.getLength());
if(req.equals("quit"))
{System.out.println("Client Terminated");break;}
System.out.println("String recieved from client: " + req);
rev = new String((new StringBuffer(req)).reverse());
if(rev.equals(req))
rsp="The given string " + req + " is a palindrome";
else
rsp="The given string " + req + " is not a palindrome";
DatagramPacket outDgp=new DatagramPacket (rsp.getBytes(),
rsp.length(), senderAddress, senderPort);
ss.send(outDgp);
}
ss.close();
}
catch(Exception e) { System.out.println("Exception "+e);}
}
}

Client Program:
import java.io.*;
import java.net.*;

public class UDPClientPalindrome


{
public static void main(String args[])
{
InetAddress host;
int port=7896;
try
{
host = InetAddress.getLocalHost();
DatagramSocket client=new DatagramSocket();
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
System.out.print("Enter a String : ");
String str=br.readLine();

- 23 -
Msc I.T Part I Advanced Computer
Networks

DatagramPacket outDgp =new DatagramPacket (str.getBytes(),


str.length(), host,port);
client.send(outDgp);
if(str.equals("quit"))
System.out.println("Client Terminated");break;
byte buffer[]=new byte[256];
DatagramPacket inDgp =new
DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new String(inDgp.getData(),0,inDgp.getLength());
System.out.println("The Answer from server:");
System.out.println(rsp);
}
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//End of main
}

Output of Server Program:

Output of Client Program:

- 24 -
Msc I.T Part I Advanced Computer
Networks

Practical 8

Aim: Create a concurrent connection-oriented server that will calculate


string length for client request.

Software Required: Java Development Kit 1.5

Description: This is a concurrent server program. Concurrent server is a


server which can handle more than one client at a time. In this program,
client will request to calculate length of string entered by user. As a
response, server will send calculated string length.

Server Program:
import java.io.*;
import java.net.*;

class StringThread extends Thread


{
Socket client;
BufferedReader br;
PrintWriter pw;

- 25 -
Msc I.T Part I Advanced Computer
Networks

public StringThread(Socket clt)


{
try
{
this.client = clt;
InetAddress cltAddress = clt.getInetAddress();
System.out.println("Client IP : "+cltAddress.getHostAddress() +
"\tPort : "+client.getPort());
br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
pw = new PrintWriter(client.getOutputStream(),true);
}
catch(Exception e)
{
System.out.println("Error ");
}
}
public void run()
{
String g="Exit";
String str;
try
{
do
{
str = br.readLine();
str = str.trim();
if ( str.indexOf("bye") == -1)
pw.println("Length of String '" + str +" ' is " +str.length());
}while(str.indexOf("bye") == -1);
if(str.indexOf("bye") == 0)
{
System.out.println("Client "+client.getLocalPort()+"
Exited");
client.close();
}
}
catch(Exception e)
{
System.out.println("Error : "+e.toString());
}
}
}
class ThreadServer
{
public static void main(String args[]) throws Exception
{
ServerSocket srv = new ServerSocket(5555);
System.out.println("Server Started :" +srv);

- 26 -
Msc I.T Part I Advanced Computer
Networks

for( ; ;)
{
Socket clt = srv.accept();
StringThread st = new StringThread(clt);
st.start();
}
}
}

Client Program:
import java.io.*;
import java.net.*;

public class ThreadClient


{
public static void main(String args[])
{
try
{
InetAddress ia = InetAddress.getLocalHost();
Socket s = new Socket(ia,5555);
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
BufferedReader br2 = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str,st;
System.out.println("'bye' to EXIT");
do
{
System.out.println("Enter the string");
str= br1.readLine();
pw.println(str);
st =br2.readLine();
if(st !=null )
System.out.println(st);
}while(str.indexOf("bye") == -1);
}
catch(Exception e)

- 27 -
Msc I.T Part I Advanced Computer
Networks

{
System.out.println("Error"+ e.toString());
}
}
}

Output of Server Program:

Output of Client Program (Port 1167):

Output of Client Program (Port 1168):

- 28 -
Msc I.T Part I Advanced Computer
Networks

Practical 9

Aim: Create a concurrent connection-less server that will calculate


string length for client request.

Software Required: Java Development Kit 1.5

Description: This is a concurrent server program. Concurrent server is a


server which can handle more than one client at a time. In this program,
client will request to calculate length of string entered by user. As a
response, server will send calculated string length.

Server Program:
import java.io.*;
import java.net.*;
import java.util.*;

class UDPPalindromeServer implements Runnable


{
DatagramPacket rec_dp,send_dp,status_dp;
DatagramSocket server;
public static void main(String args[])throws Exception
{
UDPPalindromeServer udp_pal=new UDPPalindromeServer();
udp_pal.server=new DatagramSocket(22222);
try
{
Thread t=new Thread(udp_pal);
t.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}

- 29 -
Msc I.T Part I Advanced Computer
Networks

public void run()


{
try
{
InetAddress add=InetAddress.getLocalHost();
byte send_buff[]=new byte[1024];
byte rec_buff[]=new byte[1024];
byte status_buff[]=new byte[256];
System.out.println("Welcome to UDP Server");
while (true)
{
rec_dp=new
DatagramPacket(rec_buff,rec_buff.length,add,22222);
server.receive(rec_dp);
String in_val=new String(rec_dp.getData(),0,rec_dp.getLength());
in_val=in_val.trim();
String rev=new String((new StringBuffer(in_val)).reverse());
String answer;
if (in_val.equalsIgnoreCase(rev))
answer="The given String is a Palindrome";
else
answer="The given String is Not a Palindrome";
send_buff=answer.getBytes();
send_dp=new DatagramPacket (send_buff, send_buff.length,
rec_dp. getAddress(), rec_dp.getPort());
server.send(send_dp);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Client Program:
import java.io.*;
import java.net.*;

class UDPPalindromeClient
{
public static void main(String args[])throws Exception
{
DatagramSocket server=new DatagramSocket();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress add=InetAddress.getLocalHost();
byte send_buff[]=new byte[1024];
byte rec_buff[]=new byte[1024];

- 30 -
Msc I.T Part I Advanced Computer
Networks

byte status_buff[]=new byte[256];


System.out.println("\nCheck Palindrome or not");
while (true)
{
System.out.print("\nEnter String: ");
String val=br.readLine();
send_buff=val.getBytes();
DatagramPacket send_dp=new
DatagramPacket(send_buff,send_buff.length,add,22222);
server.send(send_dp);

DatagramPacket rec_dp=new
DatagramPacket(rec_buff,rec_buff.length);
server.receive(rec_dp);
String result=new String(rec_dp.getData());
result=result.trim();
System.out.println("\n"+result+"\n");

System.out.print("\nTo Exit Enter x or X,press enter to continue:


");
String s=br.readLine();

if (s.equals("X") || s.equals("x") )
{
br.close();
server.close();
System.exit(0);
}
}
}
}

- 31 -
Msc I.T Part I Advanced Computer
Networks

Output of Server Program:

Output of Client Program:

Output of Client Program:

- 32 -
Msc I.T Part I Advanced Computer
Networks

Practical 10

Aim: Write a program to implement file transfer protocol.

Software Required: Java Development Kit 1.5

Description:

Server Program:
import java.io.*;
import java.net.*;
class TCPFileServer implements Runnable
{
public static void main(String args[])throws Exception
{
TCPFileServer fserver=new TCPFileServer();
Thread t=new Thread(fserver);
t.start();
}
public void run()
{
InputStream is=null;
OutputStream os=null;
BufferedReader in_net=null, file_read=null;
PrintWriter pw=null;
ServerSocket server=null;
Socket client=null;
try
{
System.out.println("Server Started\n");
server=new ServerSocket(30033);
client=server.accept();
System.out.println("Client Connected\n");

is=client.getInputStream();
os=client.getOutputStream();
in_net=new BufferedReader(new
InputStreamReader(client.getInputStream()));
pw=new PrintWriter(os);
String s,file_name;
file_name=in_net.readLine();
file_name=file_name.trim();
File f=new File(file_name);
if (f.exists())
{
file_read=new BufferedReader(new FileReader(f));
while ((s=file_read.readLine()) != null)
{

- 33 -
Msc I.T Part I Advanced Computer
Networks

pw.println(s);
pw.flush();
}
file_read.close();
}
System.out.println("File Flushed");
in_net.close();
client.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Client Program:
import java.io.*;
import java.net.*;
import java.lang.*;

public class TCPFileClient


{
public static void main(String args[]) throws Exception
{
Socket echosocket = null;
BufferedReader in = null, ins=null, d=null;
PrintWriter pw=null,filename=null;
try
{
echosocket = new Socket(InetAddress.getLocalHost(),30033);
d = new BufferedReader(new
InputStreamReader(echosocket.getInputStream()));
ins = new BufferedReader(new InputStreamReader(System.in));
pw=new PrintWriter(echosocket.getOutputStream());
filename=new PrintWriter(echosocket.getOutputStream());
}
catch(Exception e)
{
System.out.println("\nError in Connection\n :" +e );
}
System.out.println("\nFile Transfer Protocol");

System.out.print("\nEnter File in Server with File Extension: - ");


String line=ins.readLine();
line=line.trim();
filename.println(line);
filename.flush();
String file_ext=line.substring(line.indexOf("."));

- 34 -
Msc I.T Part I Advanced Computer
Networks

String new_filename;
System.out.print("\nEnter New File Name: - ");
new_filename=ins.readLine();
new_filename=new_filename.trim();

String new_file=new_filename+file_ext;
String userinput;
File f=new File(new_file);
FileWriter sp=new FileWriter(f);
while((userinput = d.readLine())!=null)
{
System.out.println(userinput);
sp.write(userinput);
sp.flush();
Thread.sleep(1000);
}
System.out.println("\nFile Transfer Done");
d.close();
echosocket.close();
}
}

Output of Server Program:

- 35 -
Msc I.T Part I Advanced Computer
Networks

Output of Client Program:

Practical 11

Aim: Write a program for chat server.

Software Required: Java Development Kit 1.5

- 36 -
Msc I.T Part I Advanced Computer
Networks

Server Program:
import java.io.*;
import java.net.*;

public class ChatServer


{
Socket clientSocket;
ServerSocket server;
PrintWriter remoteOut;
BufferedReader remoteIn,userIn;

/** Creates a new instance of Chat */


public ChatServer()
{
try
{
server = new ServerSocket(2345);
System.out.println("Starting Server");
clientSocket = server.accept();
System.out.println("Client Connected");
remoteIn = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
remoteOut = new PrintWriter(clientSocket.getOutputStream(),true);
userIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Configured.Start chatting");
while(true)
{
String s = "";
System.out.println("RECEIVED: " + (s = remoteIn.readLine()));
if(s.equals("bye"))
break;
System.out.print("SEND: ");

remoteOut.println((s = userIn.readLine()));
if(s.equals("bye"))
break;
}
System.out.println("Shutting Server");
remoteIn.close();
remoteOut.close();
userIn.close();
clientSocket.close();
server.close();
}
catch(Exception e)
{
System.out.println(e);
}

- 37 -
Msc I.T Part I Advanced Computer
Networks

public static void main(String[] args)


{
try
{
new ChatServer();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Client Program:
import java.io.*;
import java.net.*;

public class ChatClient


{
Socket clientSocket;
PrintWriter remoteOut;
BufferedReader remoteIn,userIn;
public ChatClient ()
{
try
{
System.out.println("Client Started");
clientSocket = new Socket("localhost",2345);
System.out.println("Connected to server.Configuring...");
remoteIn = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
remoteOut = new PrintWriter(clientSocket.getOutputStream(),true);
userIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Configured.\nStart Chatting");
while(true)
{
String s = "";
System.out.print("SEND: ");
remoteOut.println((s = userIn.readLine()));
if(s.equals("bye"))
break;

System.out.println("RECEIVED: " + (s = remoteIn.readLine()));


if(s.equals("bye"))
break;
}
System.out.println("Exiting...");

- 38 -
Msc I.T Part I Advanced Computer
Networks

remoteIn.close();
remoteOut.close();
userIn.close();
clientSocket.close();
}
catch (Exception e) { System.out.println(e); }
}
public static void main(String[] args)
{
try
{
new ChatClient();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output of Server Program:

Output of Client Program:

- 39 -
Msc I.T Part I Advanced Computer
Networks

- 40 -

You might also like