Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

BE-CSE-IT Network Lab Manual

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

Camellia Institute of Technology

Department of Computer Science and Engineering

LAB MANUAL

NETWORK PROGRAMMING LAB


BE(IT) VII Semester

In charge: Gopal Kundu


CONTENT

Sl.no. Titles Remarks

01 Looking up internet address

02 Implementation of port scanner

03 Implementation of finger client

04 Implementation of ping programming

05 Implementation of peer to peer communication using UDP

06 Implementation of socket program for UDP Echo Client and Echo


Server

07 Implementation of Client Server Communication Using TCP

08 Implementation of Client server Application for chat

09 Java multicast programming

10 Client server Communication using object stream

11 Client server Communication using byte stream

12 Implementation of CRC

13 Message passing using Message Window

14 Message Passing using Group Window

15 Implementation of Online test for a Single Client


Ex. No. 1.a

Date:

Looking up internet address of local host


Aim

To find the IP address of a local host using java program

Theory

Inet Address

public class InetAddress


extends Object
implements Serializable

It is a class in Java which represents an Internet Protocol (IP) address. An instance of an


InetAddress consists of an IP address and possibly corresponding hostname. The Class
represents an Internet address as Two fields: 1- Host name (The String)=Contain the name of the
Host.2- Address(an int)= The 32 bit IP address. These fields are not public, so we can’t Access
them directly. There is not public constructor in InetAddress class, but it has 3 static methods
that returns suitably initialized InetAddress Objects namely Public String getHostName() , public
byte[] getAddress() and public String getHostAddress()

getLocalHost()

public static InetAddress getLocalHost()


throws UnknownHostException

Returns the address of the local host. This is achieved by retrieving the name of the host from the
system, then resolving that name into an InetAddress.

Note: The resolved address may be cached for a short period of time.

If there is a security manager, its checkConnect method is called with the local host name and -1
as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress
representing the loopback address is returned.

Returns:
the address of the local host.
Throws:
UnknownHostException - if the local host name could not be resolved into an address.
SOURCE CODE:

import java.util.*;

import java.lang.*;

import java.net.*;

public class getOwnIP

public static void main(String args[])throws UnknownHostException

try

InetAddress IPO=InetAddress.getLocalHost();

System.out.println("IP of this system="+IPO.getHostAddress());

catch(Exception e)

System.out.println("Exception caught="+e.getMessage());

SAMPLE INPUT/OUTPUT:

E:\EX1>javac getOwnIP.java

E:\EX1>java getOwnIP

IP of this system=10.1.60.11
Ex. No. 1.b

Date:

Looking up internet address of Remote host


Aim

To find the IP address of a remote host using java program

Theory

1. getByName

public static InetAddress getByName(String host)


throws UnknownHostException

Determines the IP address of a host, given the host's name.

The host name can either be a machine name, such as "java.sun.com", or a textual
representation of its IP address. If a literal IP address is supplied, only the validity of the address
format is checked.

For host specified in literal IPv6 address, either the form defined in RFC 2732 or the
literal IPv6 address format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
supported. See here for a description of IPv6 scoped addresses.

Parameters:
host - the specified host, or null.
Returns:
an IP address for the given host name.
Throws:
UnknownHostException - if no IP address for the host could be found, or if a scope_id was
specified for a global IPv6 address.
SecurityException - if a security manager exists and its checkConnect method doesn't allow
the operation
SOURCE CODE:

import java.util.*;

import java.lang.*;

import java.net.*;

public class getRemoteIP

public static void main(String args[])

try

InetAddress IPO=InetAddress.getByName(args[0]);

System.out.println("IP of this system = " +IPO);

catch(Exception e)

System.out.println("Exception caught = "+e.getMessage());

SAMPLE INPUT/OUTPUT:

E:\EX1>javac getRemoteIP.java

E:\EX1>java getRemoteIP

IP of this system = GFL-335/10.1.60.11


Ex. No. 2.

Date:

Implementation of port scanner


Aim

To implement the port scanner using java program

Theory

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 on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address and
port of the client. It needs a new socket 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.

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 to.

An endpoint is a combination of an IP address and a port number. Every TCP connection


can be uniquely identified by its two endpoints. That way you can have multiple connections
between your host and the server.

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.

Socket constructor

public Socket(InetAddress address, int port) throws IOException

Creates a stream socket and connects it to the specified port number at the specified IP address.

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

If there is a security manager, its checkConnect method is called with the host address
and port as its arguments. This could result in a SecurityException.

Parameters:
address - the IP address.
port - the port number.

Socket close method

public void close() throws IOException


Closes this socket.

Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
Once a socket has been closed, it is not available for further networking use (i.e. can't
be reconnected or rebound). A new socket needs to be created.

Closing this socket will also close the socket's InputStream and OutputStream.

SOURCE CODE:

import java.net.*;

import java.io.*;

public class PortScanner

public static void main(String args[])

int startPortRange = 0;

int stopPortRange = 0;

int n=1;

startPortRange = Integer.parseInt(args[0]);

stopPortRange = Integer.parseInt(args[1]);

for(int i=startPortRange; i<=stopPortRange; i++)

try

Socket Serversok=new Socket("127.0.0.1",i);

System.out.println("Port in use : "+i);

Serversok.close();

n=0;

catch(Exception e)

{}
if(n!=0)

System.out.println("Port not in use : "+i);

n=1;

SAMPLE INPUT/OUTPUT:

E:\EX2>javac PortScanner.java

E:\EX2>java PortScanner 132 137

Port not in use : 132

Port not in use : 133

Port not in use : 134

Port not use : 135

Port not in use : 136

Port not in use : 137

E:\EX2>java PortScanner 442 447

Port not in use : 442

Port not in use : 443

Port not in use : 444

Port not use : 445

Port not in use : 446

Port not in use : 447


Ex. No. 3.

Date:

Implementation of finger client


Aim

To implement the finger client using java program

Theory

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 server can now communicate by writing to and reading from the socket.

Class Writer
public abstract class Writer extends Object implements Appendable, Closeable, Flushable

Abstract class for writing to character streams. The only methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override
some of the methods defined here in order to provide higher efficiency, additional functionality,
or both.

Methods

InputStream getInputStream()
Returns an input stream for this socket.

OutputStream getOutputStream()
Returns an output stream for this socket.

void close()
Closes this socket.
SOURCE CODE FOR CLIENT:

import java.io.BufferedInputStream;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.Writer;

import java.net.Socket;

public class Main

public final static int DEFAULT_PORT=79;

public static void main(String args[]) throws Exception

String hostname="localhost";

Socket connection=null;

connection=new Socket(hostname,DEFAULT_PORT);

Writer out=new OutputStreamWriter(connection.getOutputStream(),"8859_1");

out.write("\r\n");

InputStream raw=connection.getInputStream();

BufferedInputStream buffer=new BufferedInputStream(raw);

InputStreamReader in=new InputStreamReader(buffer,"8859_1");

int c;

while((c=in.read())!=-1)

{
if((c>=32 && c<127)||c=='\t'||c=='\r'||c=='\n')

System.out.write(c);

connection.close();

SOURCE CODE FOR SERVER:

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.InetSocketAddress;

import java.net.ServerSocket;

import java.net.Socket;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

import java.util.Set;

public class New

public static void readPlan(String userName,PrintWriter pw)throws Exception

FileReader file=new FileReader(userName+".plan");

BufferedReader buff=new BufferedReader(file);

boolean eof=false;

pw.println("\n userName:"+userName +"\n");

while(!eof)

String line=buff.readLine();

if(line==null)

eof=true;

else

pw.println(line);

buff.close();

public static void main(String args[])throws Exception

ServerSocketChannel sockChannel=ServerSocketChannel.open();

sockChannel.configureBlocking(false);
InetSocketAddress server=new InetSocketAddress("localhost",79);

ServerSocket socket=sockChannel.socket();

socket.bind(server);

Selector selector=Selector.open();

sockChannel.register(selector,SelectionKey.OP_ACCEPT);

while(true)

selector.select();

Set keys=selector.selectedKeys();

Iterator it=keys.iterator();

while(it.hasNext())

SelectionKey selKey=(SelectionKey)it.next();

it.remove();

if(selKey.isAcceptable())

ServerSocketChannel selChannel=(ServerSocketChannel)selKey.channel();

ServerSocket selSocket=selChannel.socket();

Socket connection=selSocket.accept();

InputStreamReader isr=new InputStreamReader(connection.getInputStream());

BufferedReader is=new BufferedReader(isr);

PrintWriter pw=new PrintWriter(new


BufferedOutputStream(connection.getOutputStream()),false);

pw.println("NIO finger server");

pw.flush();
String outLine=null;

String inLine=is.readLine();

if(inLine.length()>0)

outLine=inLine;

readPlan(outLine, pw);

pw.flush();

pw.close();

is.close();

connection.close();

SAMPLE INPUT/OUTPUT:

E:\EX3>javac New.java

E:\EX3>java New

E:\EX3>javac Main.java

E:\EX3>java Main

NIO finger server


Ex. No. 4.

Date:

Implementation of ping programming


Aim

To implement the ping programming using java program

Theory

Inetaddress

This class represents an Internet Protocol (IP) address.

getByName

public static InetAddress getByName(String host)


throws UnknownHostException
Determines the IP address of a host, given the host's name.

The host name can either be a machine name, such as "java.sun.com", or a textual representation
of its IP address. If a literal IP address is supplied, only the validity of the address format is
checked.

Parameters:
host - the specified host, or null.
Returns:
an IP address for the given host name.

isReachable

public boolean isReachable(NetworkInterface netif,


int ttl,
int timeout)
throws IOException
Test whether that address is reachable. Best effort is made by the implementation to try to
reach the host, but firewalls and server configuration may block requests resulting in a
unreachable status while some specific ports may be accessible. A typical implementation will
use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a
TCP connection on port 7 (Echo) of the destination host.

The network interface and ttl parameters let the caller specify which network interface
the test will go through and the maximum number of hops the packets should go through. A
negative value for the ttl will result in an IllegalArgumentException being thrown.
The timeout value, in milliseconds, indicates the maximum amount of time the try
should take. If the operation times out before getting an answer, the host is deemed
unreachable. A negative value will result in an IllegalArgumentException being thrown.

Parameters:
netif - the NetworkInterface through which the test will be done, or null for any
interface ttl - the maximum numbers of hops to try or 0 for the default
timeout - the time, in milliseconds, before the call aborts
Returns:
a Boolean indicating if the address is reachable.

SOURCE CODE:

import java.net.*;

import java.io.*;

public class Ping

public static void main(String args[])

System.out.println("Pinging status");

String ipa="GFL-335";

try

InetAddress IPA=InetAddress.getByName("Gfl-335");

System.out.println("Sending ping request to " +ipa);

boolean status=IPA.isReachable(50000);

if(status)

System.out.println("Status : Host is reachable");

else

System.out.println("Status : Host is not reachable");


}

catch(IOException e)

System.out.println("Host does not exist");

SAMPLE INPUT/OUTPUT:

E:\EX4>javac Ping.java

E:\EX4>java Ping

Pinging status

Sending ping request to GFL-335

Status : Host is reachable


Ex. No. 5.

Date:

Implementation of peer to peer communication using UDP


Aim

To implement the peer to peer communication through UDP using java program

Theory

Peer to peer communication

P2P, P-to-P and P2P communications, peer-to-peer communication refers to the


transmission between two peer computers over a network. P2P became widely known by
computer users as they began sharing MP3s and other files over P2P networks

UDP

UDP (User Datagram Protocol) is a communications protocol that offers a limited


amount of service when messages are exchanged between computers in a network that uses the
Internet Protocol (IP).

UDP Datagram

UDP network traffic is organized in the form of datagrams . A datagram comprises one
message unit. The first eight (8) bytes of a datagram contain header information and the
remaining bytes contain message data.

A UDP datagram header consists of four (4) fields of two bytes each:

 source port number


 destination port number
 datagram size
 checksum

UDP port numbers allow different applications to maintain their own channels for data
similar to TCP. UDP port headers are two bytes long; therefore, valid UDP port numbers range
from 0 to 65535.
The UDP datagram size is a count of the total number of bytes contained in header and data
sections. As the header length is a fixed size, this field effectively tracks the length of the
variable-sized data portion (sometimes called payload). The size of datagrams varies depending
on the operating environment but has a maximum of 65535 bytes.

UDP checksums protect message data from tampering. The checksum value represents an
encoding of the datagram data calculated first by the sender and later by the receiver. Should an
individual datagram be tampered with or get corrupted during transmission, the UDP protocol
detects a checksum calculation mismatch. In UDP, checksumming is optional as opposed to TCP
where checksums are mandatory.

Datagram Socket

public class DatagramSocket


extends Object
implements Closeable
This class represents a socket for sending and receiving datagram packets.

A datagram socket is the 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.

BufferedReader class

The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.

SOURCE CODE FOR CLIENT:

import java.io.*; import

java.net.*;

class UDPClient

public static void main(String args[])throws IOException

BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clisock=new DatagramSocket();

InetAddress IPA=InetAddress.getByName("GFL-335"); byte[]


receivedata=new byte[1024];

byte[] senddata=new byte[1024];

String sentence=inFromUser.readLine(); senddata

=sentence.getBytes();

DatagramPacket sendpack=new DatagramPacket(senddata,senddata.length,IPA,9876);

clisock.send(sendpack);

DatagramPacket recpack=new DatagramPacket(receivedata,receivedata.length);

clisock.receive(recpack);

String msentence=new String(recpack.getData());

System.out.println("From Server : "+ msentence);

clisock.close();

SOURCE CODE FOR SERVER:

import java.io.*; import

java.net.*;

class UDPServer

public static void main(String args[])throws IOException

DatagramSocket sersock=new DatagramSocket(9876);

byte[] receivedata=new byte[1024];

byte[] senddata=new byte[1024];

while(true)

{
DatagramPacket recpack=new DatagramPacket(receivedata,receivedata.length);

sersock.receive(recpack);

String sentence=new String(recpack.getData());

System.out.println("Received : "+ sentence); InetAddress

IPA=recpack.getAddress();

int port=recpack.getPort();

String csentence=sentence.toUpperCase();

senddata =csentence.getBytes();

DatagramPacket sendpack=new DatagramPacket(senddata,senddata.length,IPA,port);

sersock.send(sendpack);

SAMPLE INPUT/OUTPUT:

E:\EX5>javac UDPServer.java

E:\EX5>java UDPServer

Received : Hi Server

E:\EX5>javac UDPClient.java

E:\EX5>java UDPClient Hi

Server

From Server : HI SERVER


Ex. No. 6.

Date:

Implementation of socket program for UDP Echo Client and Echo Server
Aim

To implement a socket program for UDP Echo Client and Echo Server using java
program

Theory

DatagramSocket

public class DatagramSocket


extends Object
implements Closeable
This class represents a socket for sending and receiving datagram packets.

A datagram socket is the 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.

BufferedReader class

The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
SOURCE CODE FOR CLIENT:

import java.net.*;

import java.io.*;

import java.lang.*;

public class EC

public static void main(String args[])throws IOException

byte[] buff=new byte[1024];

DatagramSocket soc=new DatagramSocket(9999);

String s="From client-Hello Server";

buff=s.getBytes();

InetAddress a=InetAddress.getByName("Gfl-335");

DatagramPacket pac=new DatagramPacket(buff,buff.length,a,8888);

soc.send(pac);

System.out.println("End of sending");

byte[] buff1=new byte[1024];

buff1=s.getBytes();

pac=new DatagramPacket(buff1,buff1.length);

soc.receive(pac);

String msg=new String(pac.getData());

System.out.println(msg);
System.out.println("End of programming");

SOURCE CODE FOR SERVER:

import java.net.*;

import java.io.*;

import java.lang.*;

public class ES

public static void main(String args[])throws IOException

byte[] buff=new byte[512];

DatagramSocket soc=new DatagramSocket(8888);

DatagramPacket pac=new DatagramPacket(buff,buff.length );

System.out.println("server started");

soc.receive(pac);

String msg=new String(pac.getData());

System.out.println(msg);

System.out.println("End of reception");
String s="From Server-Hello client"; byte[]

buff1=new byte[512]; buff1=s.getBytes();

InetAddress a=pac.getAddress(); int

port=pac.getPort();

pac=new DatagramPacket(buff,buff1.length,a,port);

soc.send(pac);

System.out.println("End of sending");

SAMPLE INPUT/OUTPUT:

E:\EX6>javac ES.java

E:\EX6>java ES server

started

From client-Hello Server

End of reception End of

sending

E:\EX6>javac EC.java

E:\EX6>java EC
End of sending

From client-Hello Server End

of programming

Ex. No. 7.

Date:

Implementation of Client Server Communication Using TCP


Aim

To implement Client Server Communication using TCP through Java programming.

Theory

DatagramSocket

public class DatagramSocket


extends Object
implements Closeable
This class represents a socket for sending and receiving datagram packets.

A datagram socket is the 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.

BufferedReader class

The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.

TCP

TCP is one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only
with packets, TCP enables two hosts to establish a connection and exchange streams of data.
TCP guarantees delivery of data and also guarantees that packets will be delivered in the same
order in which they were sent.
SOURCE CODE FOR CLIENT:

import java.lang.*;

import java.net.*;

import java.io.*;

class CliTCP

public static void main(String args[])

try

Socket skt=new Socket("Gfl-335",1234);

BufferedReader in=new BufferedReader(new InputStreamReader(skt.getInputStream()));

System.out.println("Received string:");

while(!in.ready())

System.out.println(in.readLine());

System.out.println("\n");

in.close();

catch(Exception e)

System.out.println("Whoops! It didn't work! \n");


}

SOURCE CODE FOR SERVER

import java.lang.*;

import java.net.*;

import java.io.*;

class SerTCP

public static void main(String args[])

String data="Welcome";

try

ServerSocket s=new ServerSocket(1234);

Socket skt=s.accept();

System.out.println("Server has connected! \n");

PrintWriter out=new PrintWriter(skt.getOutputStream(),true);

System.out.println("Sending string: \n "+data+"\n");


out.print(data);

out.close();

skt.close();

s.close();

catch(Exception e)

System.out.println("Whoops! It didn't work! \n");

SAMPLE INPUT/OUTPUT:

E:\EX7>javac SerTCP.java

E:\EX7>java SerTCP

Server has connected!

Sending string:

Welcome

E:\EX7>javac CliTCP.java

E:\EX7>java CliTCP

Received string:

Welcome
Ex. No. 8.

Date:

Implementation of Client server Application for chat


Aim

To write a java program to implement client server application for chat.

Theory

Inet Address

public class InetAddress


extends Object
implements Serializable

It is a class in Java which represents an Internet Protocol (IP) address. An instance of an


InetAddress consists of an IP address and possibly corresponding hostname. The Class
represents an Internet address as Two fields: 1- Host name (The String)=Contain the name of the
Host.2- Address(an int)= The 32 bit IP address. These fields are not public, so we can’t Access
them directly. There is not public constructor in InetAddress class, but it has 3 static methods
that returns suitably initialized InetAddress Objects namely Public String getHostName() , public
byte[] getAddress() and public String getHostAddress()

BufferedReader class

The BufferedReader class is used for fast reading operations of texts from a character-
input stream. It can be used to read single characters, arrays, and lines of data. The size of buffer
may or may not be specified. The readLine() method of the BufferedReader class can be used to
get the next line of characters from a file, and the skip(long n) method can be used to skip n
number of characters.
SOURCE CODE FOR CLASS CHAT:

import java.io.*;

import java.net.*;

import java.lang.String.*;

class chat extends Thread

Socket soc;

InetAddress addr;

ServerSocket s;

BufferedReader d;

BufferedReader in;

PrintWriter out;

String name;

public chat(Socket s)throws IOException

soc= s;

d=new BufferedReader(new InputStreamReader(System.in));

in=new BufferedReader(new InputStreamReader(soc.getInputStream()));

out=new PrintWriter(new BufferedWriter(new


OutputStreamWriter(soc.getOutputStream())),true);

start();

}
public void run()

String str;

try

out.println("Chat sessions begins..");

out.println("Server: Your name please : ");

str=in.readLine();

name=str;

addr=soc.getInetAddress();

System.out.println("Message:");

str=d.readLine();

while(true)

out.println(str);

str=in.readLine();

if(str.equalsIgnoreCase("end"))

break;

System.out.println(name+":>"+str);

System.out.println("Message : ");

str=d.readLine();

catch(IOException e)

{}
catch(NullPointerException e)

System.out.println(name+" quit chat");

SOURCE CODE FOR CHAT CLIENT:

import java.io.*;

import java.net.*;

class chatclient

public static Socket soc;

public static void main(String args[])throws IOException

try

InetAddress a=InetAddress.getLocalHost();

soc=new Socket(a,0202);

BufferedReader d=new BufferedReader(new InputStreamReader(System.in));


BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()));

PrintWriter out=new PrintWriter(new BufferedWriter(new BufferedWriter(new


OutputStreamWriter(soc.getOutputStream()))),true);

String s;

s=in.readLine();

System.out.println(s);

s=in.readLine();

System.out.println(s);

s=d.readLine();

while(true)

out.println(s);

s=in.readLine();

System.out.println("Server:> "+s);

if(s.equalsIgnoreCase("Chat is closing"))

break;

System.out.println("Message : ");

s=d.readLine();

if(s.equalsIgnoreCase("end"))

break;

finally

soc.close();
}

SOURCE CODE FOR CHAT SERVER:

import java.io.*;

import java.net.*;

class chatserver

public static void main(String args[])throws IOException

ServerSocket s=new ServerSocket(0202);

try

while(true)

Socket soc=s.accept();

try

new chat(soc);
}

catch(IOException e)

soc.close();

finally

s.close();

SAMPLE INPUT/OUTPUT:

E:\EX8>javac chatserver.java

E:\EX8>java chatserver

Message :

Hi Client, how are you? BE

IT:> I am fine.

E:\EX8>javac chatclient.java

E:\EX8>java chatclient Chat

sessions begins.. Server : Your

name please : BE IT

You might also like