0% found this document useful (0 votes)
28 views31 pages

"Computer Networks ": A Practical File On

This document provides information about socket programming in Java. It discusses how sockets provide communication between two computers using TCP. The key classes used are Socket for clients and ServerSocket for servers. It describes how a TCP connection is established between a client and server, with the server listening on a port using ServerSocket and the client connecting using Socket. Constructors and methods of ServerSocket like accept() are explained for listening and accepting client connections.

Uploaded by

yiet8904
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views31 pages

"Computer Networks ": A Practical File On

This document provides information about socket programming in Java. It discusses how sockets provide communication between two computers using TCP. The key classes used are Socket for clients and ServerSocket for servers. It describes how a TCP connection is established between a client and server, with the server listening on a port using ServerSocket and the client connecting using Socket. Constructors and methods of ServerSocket like accept() are explained for listening and accepting client connections.

Uploaded by

yiet8904
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

A

PRACTICAL FILE
ON

“COmPuTER NETwORks ”

submITTEd TO: submITTEd by:

ER.suNIL PANjETA ARyAN RAj


(HEAd OF dEPARTmENT) 4116008
(ECE) TH
CsE-5 sEm

dEPARTmENT OF COmPuTER sCIENCE ENGINEERING


yAmuNA INsTITuTE OF ENGINEERING & TECHNOLOGy ,GAd H O L I

yAmuNANAGAR
INDEX

S.NO NAME OF PRACTICAL DATE SIGNATURE

1. To Briefly explain socket Programming in java.

2. Write a program to enter statements from client


side & execute it in server ,respond with over
message
3. Write a program to multiply a number with 2 on the
client side & display the output on the server side

4. To write a program for TCP echo client server


system connection.

5. To study TCP/UDP Performance.

6. WAP to write a program for date server and client.

7. To write a program for chat server and client.


Practical No. 1

AIm : TO bRIEFLy ExPLAIN sOCkET PROGRAmmING IN jAvA .

sOFTwARE : bLuE j(v 4.1.4)


sOCkET :
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 java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them

jAvA sOCkET PROGRAmmING :

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.

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.

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.

sERvERsOCkET CLAss mETHOds


The java.net.ServerSocket class is used by server applications to obtain a port and listen for client
requests.
CONsTRuCTORs usEd :

Sr.No. Name Syntax Description Parameters Throws

1 ServerSocket(int) Public Creates a server socket on a port - the IOException


ServerSocket(int specified port. A port of 0 creates a port - if an I/O
port) throws socket on any free port. number, error occurs
IOException or 0 to use when
The maximum queue length for any free opening the
incoming connection indications (a port. socket.
request to connect) is set to 50. If a
connection indication arrives when
the queue is full, the connection is
refused.

If the application has specified a


server socket factory, that
factory's createSocketImpl method
is called to create the actual socket
implementation. Otherwise a "plain"
socket is created.

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.

If the application has specified a


server socket factory, that
factory's createSocketImpl method
is called to create the actual socket
implementation. Otherwise a "plain"
socket is created

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.

4 ServerSocket() public Creates an unbound server socket. ------ IOException


ServerSocket() When using this constructor, use the
throws bind() method when you are ready
IOException to bind the server socket.

mETHOds usEd :

Sr.No. Name Syntax Description Returns/


throws
1 getInetAddress public InetAddress Returns the local address of the address to which this
getInetAddress() this server socket. socket is
connected, or null if
the socket is not yet
connected
2 getLocalPort public int Returns the port on which this the port number to which
getLocalPort() socket is listening. this socket is listening.

3 Accept public Socket accept() Listens for a connection to be Throws: IOException if


throws IOException made to this socket and an I/O error
accepts it. The method blocks occurs when waiting for
until a connection is made. a connection

4 implAccept protected final void Subclasses of ServerSocket -----------


implAccept(Socket s) use this method to override
throws IOException accept() to return their own
subclass of socket. So a
FooServerSocket will
typically hand this method
an empty FooSocket(). On
return from implAccept the
FooSocket will be connected
to a client.

5 Close public void close() Closes this socket. Throws:IOException


throws IOException if an I/O error occurs
when closing the socket.
6 setSoTimeout public synchronized Enable/disable -----------
void setSoTimeout(int SO_TIMEOUT with the
timeout) throws specified timeout, in
SocketException milliseconds. With this option
set to a non-zero timeout, a
call to accept() for this
ServerSocket will block for
only this amount of time. If
the timeout expires,
a java.io.InterruptedIOExcept
ion is raised, though the
ServerSocket is still valid.
The option must be enabled
prior to entering the blocking
operation to have effect. The
timeout must be > 0. A
timeout of zero is interpreted
as an infinite timeout.

7 getSoTimeout public synchronized int Retrive setting for -------------


getSoTimeout() throws SO_TIMEOUT. 0 returns
IOException implies that the option is
disabled (i.e., timeout of
infinity).

8 toString public String toString() Returns the implementation a string representation of


address and implementation this socket.
port of this socket as
a String.

9 SetSocketFactory public static Sets the server socket Throws: IOException if


synchronized void implementation factory for the an I/O error occurs when
setSocketFactory(Socke application. The factory can be setting the socket
tImplFactory fac) specified only once. factory.
throws IOException Throws: SocketExceptio
When an application creates a n if the factory has
new server socket, the socket already been defined.
implementation
factory's createSocketImpl met
hod is called to create the
actual socket implementation.
sOCkET CLAss mETHOds :
The java.net.Socket class represents the socket that both the client and the server use to communicate
with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a
Socket object from the return value of the accept() method.

Constructors used:

Sr.N Name Syntax Description Parameters Throws


o.

1 Socket() protected Socket() Creates an unconnected socket, ------ -------


with the system-default type of
SocketImpl.
2 Socket(InetAddre Creates an unconnected Socket ------- --------
ss , int) protected with a user-specified
Socket(SocketImpl SocketImpl.
impl)throws
SocketException The impl parameter is an
instance of a SocketImpl the
subclass wishes to use on the
Socket.

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

6 Socket(String , public Creates a socket and connects address - the --------


int) Socket(InetAddress it to the specified remote remote address
address, int port, address on the specified
InetAddress remote port. The Socket will port - the remote
localAddr,int also bind() to the local address port
localPort)throws and port supplied. localAddr - the
IOException local address 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.

8 Socket(String, int public Socket() is deprecated. Use address - the IP IOExceptio


, InetAddress, int) Socket(InetAddress DatagramSocket instead for address. n
host, int port, boolean UDP transport. if an I/O
stream)throws Creates a socket and connects it port - the port error occurs
IOException to the specified port number at number. when
the specified IP address. creating the
stream - if true, socket.
If the stream argument is true, create a stream
this creates a stream socket. If socket; otherwise,
the stream argument is false, it create a datagram
creates a datagram socket. 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.
mETHOds usEd:

Sr.No. Name Syntax Description Returns/


throws

1 getInetAddress public InetAddress Returns the address to which the remote IP


getInetAddress() the socket is connected. address to
which this
socket is
connected.
2 getLocalAddress public InetAddress Gets the local address to which --------
getLocalAddress() the socket is bound.

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.

7 setTcpNoDelay public void Enable/disable --------


setTcpNoDelay(boolea TCP_NODELAY
n on) throws (disable/enable Nagle's
SocketException algorithm).

8 getTcpNoDelay public boolean Tests if TCP_NODELAY is --------


getTcpNoDelay() enabled.
throws SocketException

9 setSoLinger public void Enable/disable SO_LINGER --------


setSoLinger(boolean with the specified linger time.
on,
int val)
throws SocketException

10 getSoLinger public int getSoLinger() Returns setting for ---------


throws SocketException SO_LINGER. -1 returns
implies that the option is
disabled.

11 setSoTimeout public synchronized Enable/disable ----------


void setSoTimeout(int SO_TIMEOUT with the
timeout) throws specified timeout, in
SocketException milliseconds. With this option
set to a non-zero timeout, a
read() call on the InputStream
associated with this Socket
will block for only this amount
of time. If the timeout expires,
a java.io.InterruptedIOExce
ption is raised, though the
Socket is still valid. The
option must be enabled prior
to entering the blocking
operation to have effect. The
timeout must be > 0. A timeout
of zero is interpreted as an
infinite timeout.

12 getSoTimeout public synchronized int Returns setting for ---------


getSoTimeout() throws SO_TIMEOUT. 0 returns
SocketException implies that the option is
disabled (i.e., timeout of
infinity).

13 Close public synchronized Closes this socket. Throws:IOE


void close() throws xception
IOException if an I/O error
occurs when
closing this
socket.

14 toString public String toString() Converts this socket to Returns:


a String. a string
representation
of this socket.

15 setSocketFactory public static Sets the client socket Throws: IOE


synchronized void implementation factory for the xception if an
setSocketImplFactory(S application. The factory can be I/O error
ocketImplFactory fac) specified only once. occurs when
throws IOException setting the
When an application creates a socket
new client socket, the socket factory.
implementation
factory's createSocketImpl met Throws: Soc
hod is called to create the ketException
actual socket implementation. if the factory
is already
defined.
Practical No. 2

AIm :wRITE A PROGRAm TO ENTER sTATEmENTs FROm CLIENT


sIdE & ExECuTE IT IN sERvER ,REsPONd wITH OvER mEssAGE.

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;

public as(String address,int port)


{
try
{
socket=new Socket(address,port);
System.out.println("connected");
input=new DataInputStream(System.in);
out=new
DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
String line="";
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
try
{
input.close();
out.close();
socket.close();

}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
as client = new as("127.0.0.1",5000);
}
}

sERvER COdE:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class server{ //class name


private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

public server(int port)//class name


{
try
{
server=new ServerSocket(port);
System.out.println ("Server started");

System.out.println ("waiting for a client....");


socket= server.accept();

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;

public class clientnumb {


public static void main(String args[]) throws
UnknownHostException, IOException
{
int number, temp;
Scanner sc = new Scanner(System.in);
Socket s=new Socket("localhost",1342);
Scanner sc1=new Scanner(s.getInputStream());
System.out.println("enter any number");
number = sc.nextInt();
PrintStream p=new PrintStream(s.getOutputStream());
p.println(number);
temp=sc1.nextInt();
System.out.println(temp);
}

}
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;

public class servernumb {


public static void main(String args[]) throws
UnknownHostException, IOException
{
int number,temp;
ServerSocket s1=new ServerSocket(1342);
Socket ss=s1.accept();
Scanner sc=new Scanner(ss.getInputStream());
number=sc.nextInt();
temp=number*2;
PrintStream p=new PrintStream(ss.getOutputStream());
p.println(temp);

OuTPuT:
Practical No. 4

AIm : TO wRITE A PROGRAm FOR TCP ECHO CLIENT sERvER


sysTEm CONNECTION.

COdE:

CLIENT COdE:
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 22000);


DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

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.*;

public class TCPServer {


public static void main(String args[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(22000);
Socket connectionSocket = welcomeSocket.accept();
while(true) {

BufferedReader inFromClient = new BufferedReader(new


InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() +
'\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}

OuTPuT:
Practical No. 5

AIm-TO sTudy TCP/udP PERFORmANCE.

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

HOw udP wORks


The UDP protocol works similarly to TCP, but it throws out all the error-checking stuff. All the back-and-
forth communication introduce latency, slowing things down.

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.

COmPARIsON bETwEEN TCP ANd udP

TCP UDP

Acronym for

Transmission Control Protocol User Datagram Protocol or


Universal Datagram Protocol

Connection

TCP is a connection-oriented protocol. UDP is a connectionless protocol.

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.

Use by other protocols

HTTP, HTTPs, FTP, SMTP, Telnet DNS, DHCP, TFTP, SNMP, RIP,
VOIP.

Ordering of data packets

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

TCP header size is 20 bytes UDP Header size is 8 bytes.

Common Header Fields

Source port, Destination port, Check Sum Source port, Destination port,
Check Sum

Streaming of data

Data is read as a byte stream, no Packets are sent individually and


distinguishing indications are transmitted to are checked for integrity only if
signal message (segment) boundaries. they arrive. Packets have definite
boundaries which are honored
upon receipt, meaning a read
operation at the receiver socket
will yield an entire message as it
was originally sent.

Weight

TCP is heavy-weight. TCP requires three UDP is lightweight. There is no


packets to set up a socket connection, before ordering of messages, no tracking
any user data can be sent. TCP handles connections, etc. It is a small
reliability and congestion control. transport layer designed on top of
IP.
dIFFERENT APPLICATIONs OF TCP ANd udP

 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

AIm : TO wRITE A PROGRAm FOR dATE sERvER ANd CLIENT .

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

AIm : TO wRITE A PROGRAm FOR CHAT sERvER ANd CLIENT.

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));

System.out.println("Start the chitchat, type and press Enter


key");

String receiveMessage, sendMessage;


while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null)
//receive from server
{
System.out.println(receiveMessage); // displaying at DOS
prompt
}
}
}
}

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));

String receiveMessage, sendMessage;


while(true)
{
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}
OuTPuT:

You might also like