"Computer Networks ": A Practical File On
"Computer Networks ": A Practical File On
PRACTICAL FILE
ON
“COmPuTER NETwORks ”
yAmuNANAGAR
INDEX
Java Socket programming is used for communication between the applications running on different JRE.
It can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
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.
After the connections are established, communication can occur using I/O streams. Each socket has both
an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream,
and the client's InputStream is connected to the server's OutputStream.
2 ServerSocket(int, public Creates a server socket and binds it port - the IOException
int) ServerSocket(int to the specified local port number. A specified if an I/O error
port, port number of 0 creates a socket on port, or 0 to occurs when
int backlog) any free port. use any free opening the
throws port. socket.
IOException The maximum queue length for backlog -
incoming connection indications (a the
request to connect) is set to maximum
the count parameter. If a connection length of the
indication arrives when the queue is queue.
full, the connection is refused.
3 ServerSocket(int, public Create a server with the specified port - the IOException
int, InetAddress) ServerSocket(int port, listen backlog, and local IP local TCP
port, address to bind to. port
int backlog, The bindAddr argument can be backlog -
InetAddress used on a multi-homed host for a the listen
bindAddr) throws ServerSocket that will only accept backlog
IOException connect requests to one of its bindAddr -
addresses. If bindAddr is null, it the local
will default accepting connections InetAddress
on any/all local addresses. The port the server
must be between 0 and 65535, will bind to
inclusive.
mETHOds usEd :
Constructors used:
3 Socket(InetAddre public Socket(String . Creates a stream socket and host - the host IOExcepti
ss , int , boolean) host, int port) throws connects it to the specified name. on
UnknownHostExcepti port number on the named if an I/O
on, IOException host. port - the port error occurs
number. when
If the application has specified creating the
a server socket factory, that socket.
factory's createSocketImpl met
hod is called to create the
actual socket implementation.
Otherwise a "plain" socket is
created.
4 Socket(InetAddre public Creates a stream socket and address - the IP IOExceptio
ss , int , Socket(InetAddress connects it to the specified address. n
InetAddress, int) address, int port) port number at the specified IP if an I/O
throws IOException address. port - the port error occurs
number. when
If the application has specified creating the
a socket factory, that socket.
factory's createSocketImpl met
hod is called to create the
actual socket implementation.
Otherwise a "plain" socket is
created.
5 Socket(SocketIm public Socket(String Creates a socket and connects host - the name of --------
pl) host, int port, it to the specified remote host the remote host
InetAddress on the specified remote port. port - the remote
localAddr, The Socket will also bind() to port
int localPort) throws the local address and port
IOException supplied. localAddr - the
local address the
socket is bound to
localPort - the
local port the
socket is bound to
localPort - the
local port the
socket is bound to
7 Socket(String, int public Socket(String Socket() is deprecated. Use host - the host IOExceptio
, boolean) host, int port, boolean DatagramSocket instead for name. n
stream)throws UDP transport. if an I/O
IOException Creates a stream socket and port - the port error occurs
connects it to the specified port number. when
number on the named host. creating the
stream - socket.
If the stream argument is true, a boolean indicati
this creates a stream socket. If ng whether this is
the stream argument is false, it a stream socket or
creates a datagram socket. a datagram
socket.
If the application has specified
a server socket factory, that
factory's createSocketImpl met
hod is called to create the actual
socket implementation.
Otherwise a "plain" socket is
created.
3 getPort public int getPort() Returns the remote port to the remote
which this socket is connected. port number
to which this
socket is
connected
4 getLocalPort public int Returns the local port to which the local port
getLocalPort() this socket is bound. number to
which this
socket is
connected.
5 getInputStream public InputStream Returns an input stream for Returns:
getInputStream() this socket an input
throws IOException stream for
reading bytes
from this
socket.
Throws: IOE
xception
if an I/O error
occurs when
creating the
input stream
6 getOutputStream public OutputStream Returns an output stream for Returns:
getOutputStream() this socket. an output
throws IOException stream for
writing bytes
to this socket.
Throws: IOE
xception
if an I/O error
occurs when
creating the
output stream.
COdE:
CLIENT COdE:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class as
{
private Socket socket =null;
private DataInputStream input =null;
private DataOutputStream out = null;
}
catch(IOException i)
{
System.out.println(i);
}
}
sERvER COdE:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
System.out.println("client accepted");
in=new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
String line="";
while(!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("closing connection");
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
server server=new server(5000); }
}
OuTPuT:
Practical No. 3
AIm : wRITE A PROGRAm TO muLTIPLy A NumbER wITH 2 ON
THE CLIENT sIdE & dIsPLAy THE OuTPuT ON THE sERvER
sIdE.
COdE:
CLIENT COdE:
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
}
sERvER COdE:
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
OuTPuT:
Practical No. 4
COdE:
CLIENT COdE:
import java.io.*;
import java.net.*;
while(true)
{
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
}
// clientSocket.close();
}
}
sERvER COdE:
import java.io.*;
import java.net.*;
OuTPuT:
Practical No. 5
TCP
TCP stands for “Transmission Control Protocol.” TCP is a connection-oriented protocol in which the data
can be transferred bidirectionally after connection is being setuped. TCP is reliable and secure but
comparatively slower as it keeps the data smooth and checks error. The order of data at receiving end is
same as on sending end. Header size of TCP is 20 bytes
udP
UDP stands for “User Datagram Protocol.” UDP is connection-less protocol in which data is needed to
send in chunks. UDP don’t have error checking mechanism that is why it is less reliable but is faster in
data transferring than TCP. Header size of UDP is 8 bytes.
HOw TCP wORks
TCP is the most commonly used protocol on the Internet.
When you request a web page in your browser, your computer sends TCP packets to the web server’s
address, asking it to send the web page back to you. The web server responds by sending a stream of TCP
packets, which your web browser stitches together to form the web page. When you click a link, sign in,
post a comment, or do anything else, your web browser sends TCP packets to the server and the server
sends TCP packets back.
TCP is all about reliability—packets sent with TCP are tracked so no data is lost or corrupted in transit.
This is why file downloads don’t become corrupted even if there are network hiccups. Of course, if the
recipient is completely offline, your computer will give up and you’ll see an error message saying it can’t
communicate with the remote host.
TCP achieves this in two ways. First, it orders packets by numbering them. Second, it error-checks by
having the recipient send a response back to the sender saying that it has received the message. If the
sender doesn’t get a correct response, it can resend the packets to ensure the recipient receives them
correctly
When an app uses UDP, packets are just sent to the recipient. The sender doesn’t wait to make sure the
recipient received the packet—it just continues sending the next packets. If the recipient misses a few
UDP packets here and there, they are just lost—the sender won’t resend them. Losing all this overhead
means the devices can communicate more quickly.
UDP is used when speed is desirable and error correction isn’t necessary. For example, UDP is frequently
used for live broadcasts and online games.
For example, let’s say you’re watching a live video stream, which are often broadcast using UDP instead
of TCP. The server just sends a constant stream of UDP packets to computers watching. If you lose your
connection for a few seconds, the video may freeze or get jumpy for a moment and then skip to the current
bit of the broadcast. If you experience minor packet-loss, the video or audio may be distorted for a moment
as the video continues to play without the missing data.
TCP UDP
Acronym for
Connection
Function
As a message makes its way across the internet from UDP is also a protocol used in
one computer to another. This is connection based. message transport or transfer. This is
not connection based which means
that one program can send a load of
packets to another and that would be
the end of the relationship.
HTTP, HTTPs, FTP, SMTP, Telnet DNS, DHCP, TFTP, SNMP, RIP,
VOIP.
TCP rearranges data packets in the order specified. UDP has no inherent order as all
packets are independent of each
other. If ordering is required, it has
to be managed by the application
layer.
Speed of transfer
The speed for TCP is slower than UDP. UDP is faster because error
recovery is not attempted. It is a
"best effort" protocol.
Reliability
There is absolute guarantee that the data There is no guarantee that the
transferred remains intact and arrives in the messages or packets sent would
same order in which it was sent. reach at all.
Header Size
Source port, Destination port, Check Sum Source port, Destination port,
Check Sum
Streaming of data
Weight
Web browsing, email and file transfer are common applications that make use of TCP. TCP is
used to control segment size, rate of data exchange, flow control and network congestion.
TCP is preferred where error correction facilities are required at network interface level.
UDP is largely used by time sensitive applications as well as by servers that answer small queries
from huge number of clients.
UDP is compatible with packet broadcast - sending to all on a network and multicasting –
sending to all subscribers.
UDP is commonly used in Domain Name System, Voice over IP, Trivial File Transfer Protocol
and online games.
Practical No. 6
COdE:
CLIENT COdE:
import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("192.168.8.100",5217);
BufferedReader in=new BufferedReader(
new InputStreamReader(
soc.getInputStream()
)
);
System.out.println(in.readLine());
}
}
sERvER COdE:
import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new
DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() +
"\n");
out.close();
soc.close();
}
}
}
OuTPuT:
Practical No. 7
COdE:
CLIENT COdE:
import java.io.*;
import java.net.*;
public class GossipClient
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new
InputStreamReader(istream));
sERvER COdE:
import java.io.*;
import java.net.*;
public class GossipServer
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock = sersock.accept( );
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new
InputStreamReader(istream));