You are on page 1of 89

Annamalai University

Department of Computer Science and Engineering

LAB MANUAL

97708 – NETWORK PROGRAMMING LAB
BE(IT) VII Semester

In charge: R.Arunkumar

CONTENT
Sl.no.

Titles

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

Remarks

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.1.60.java E:\EX1>java getOwnIP IP of this system=10.11 .

If a literal IP address is supplied.if no IP address for the host could be found.com". given the host's name. or a textual representation of its IP address. either the form defined in RFC 2732 or the literal IPv6 address format defined in RFC 2373 is accepted. SecurityException . Returns: an IP address for the given host name. Throws: UnknownHostException .sun. 1. See here for a description of IPv6 scoped addresses. No. or if a scope_id was specified for a global IPv6 address. only the validity of the address format is checked. such as " java.if a security manager exists and its checkConnect method doesn't allow the operation .the specified host. Parameters: host . For host specified in literal IPv6 address.Ex. The host name can either be a machine name.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. or null. IPv6 scoped addresses are also supported.

println("IP of this system = " +IPO).getMessage()). } catch(Exception e) { System. import java.SOURCE CODE: import java.*.println("Exception caught = "+e. import java.out.util.out.*. public class getRemoteIP { public static void main(String args[]) { try { InetAddress IPO=InetAddress.getByName(args[0]). } } } .lang. System.net.*.

1.SAMPLE INPUT/OUTPUT: E:\EX1>javac getRemoteIP.60.java E:\EX1>java getRemoteIP IP of this system = GFL-335/10.11 .

No. Upon acceptance. Definition: . 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. a socket is successfully created and the client can use the socket to communicate with the server. If everything goes well. This is usually assigned by the system. the client tries to rendezvous with the server on the server's machine and port.Ex. 2. listening to the socket for a client to make a connection request. The client and server can now communicate by writing to or reading from their sockets. Date: Implementation of port scanner Aim To implement the port scanner using java program Theory Socket Normally. To make a connection request. if the connection is accepted. 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. a server runs on a specific computer and has a socket that is bound to a specific port number. On the client side. The server just waits. the server accepts the connection. 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. 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.

net. which implements a socket that servers can use to listen for and accept connections to clients. 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. Additionally.net includes the ServerSocket class. The Socket class sits on top of a platform-dependent implementation. .net package in the Java platform provides a class. int port) throws IOException Creates a stream socket and connects it to the specified port number at the specified IP address. port . That way you can have multiple connections between your host and the server. Otherwise a "plain" socket is created. Socket close method public void close() throws IOException Closes this socket. that implements one side of a two-way connection between your Java program and another program on the network. Every TCP connection can be uniquely identified by its two endpoints.the IP address. Socket constructor public Socket(InetAddress address. java. hiding the details of any particular system from your Java program.Socket class instead of relying on native code. If there is a security manager. If the application has specified a socket factory. Parameters: address . An endpoint is a combination of an IP address and a port number. By using the java. This could result in a SecurityException. its checkConnect method is called with the host address and port as its arguments. This lesson shows you how to use the Socket and ServerSocket classes.A socket is one endpoint of a two-way communication link between two programs running on the network. your Java programs can communicate over the network in a platformindependent fashion.the port number. The java. that factory's createSocketImpl method is called to create the actual socket implementation. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException. Socket.

Once a socket has been closed.e. A new socket needs to be created. Closing this socket will also close the socket's InputStream and OutputStream. can't be reconnected or rebound). it is not available for further networking use (i. .

0. startPortRange = Integer.io.*. n=0. int n=1. for(int i=startPortRange.close().*. public class PortScanner { public static void main(String args[]) { int startPortRange = 0.parseInt(args[1]). i<=stopPortRange. System.net. Serversok.i). } catch(Exception e) {} . int stopPortRange = 0. import java. i++) { try { Socket Serversok=new Socket("127.SOURCE CODE: import java.parseInt(args[0]). stopPortRange = Integer.1".out.println("Port in use : "+i).0.

} } } .if(n!=0) System.println("Port not in use : "+i).out. 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 .

A client program creates a socket on its end of the communication and attempts to connect that socket to a server. OutputStream getOutputStream() Returns an output stream for this socket. will override some of the methods defined here in order to provide higher efficiency. int). The client and server can now communicate by writing to and reading from the socket. 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. . or both. the server creates a socket object on its end of the communication. int. however. additional functionality. Most subclasses. void close() Closes this socket. 3. Methods InputStream getInputStream() Returns an input stream for this socket. When the connection is made. Closeable. The only methods that a subclass must implement are write(char[]. and close().Ex. Class Writer public abstract class Writer extends Object implements Appendable. No. flush(). Flushable Abstract class for writing to character streams.

InputStream raw=connection. public static void main(String args[]) throws Exception { String hostname="localhost". out.io.write("\r\n"). public class Main { public final static int DEFAULT_PORT=79.SOURCE CODE FOR CLIENT: import java.DEFAULT_PORT).read())!=-1) { .net."8859_1").InputStream.InputStreamReader. InputStreamReader in=new InputStreamReader(buffer."8859_1").Writer. import java. import java. BufferedInputStream buffer=new BufferedInputStream(raw). connection=new Socket(hostname.io. import java. while((c=in.getInputStream().io.Socket. Writer out=new OutputStreamWriter(connection.io.getOutputStream().io. Socket connection=null.OutputStreamWriter. import java. int c.BufferedInputStream. import java.

io.channels.channels.PrintWriter.BufferedReader.io. import java. import java.Selector.nio.channels. import java. } } SOURCE CODE FOR SERVER: import java. import java.ServerSocketChannel.nio. import java.FileReader.out.close(). import java.if((c>=32 && c<127)||c=='\t'||c=='\r'||c=='\n') { System.nio.net.net. import java.io.Socket. } } connection.InetSocketAddress.io.SelectionKey.net. import java. .write(c).InputStreamReader.BufferedOutputStream.io. import java.ServerSocket. import java.

import java.open().Set. } buff. else pw.util.readLine(). while(!eof) { String line=buff.close().println(line). pw.plan"). public class New { public static void readPlan(String userName. . import java. boolean eof=false.util.Iterator. } public static void main(String args[])throws Exception { ServerSocketChannel sockChannel=ServerSocketChannel.configureBlocking(false). sockChannel.println("\n userName:"+userName +"\n").PrintWriter pw)throws Exception { FileReader file=new FileReader(userName+". if(line==null) eof=true. BufferedReader buff=new BufferedReader(file).

channel().SelectionKey. Set keys=selector. it.socket().println("NIO finger server").getInputStream()). sockChannel.false). Socket connection=selSocket. while(it. pw.OP_ACCEPT). while(true) { selector. BufferedReader is=new BufferedReader(isr). Iterator it=keys.select(). ServerSocket selSocket=selChannel. ServerSocket socket=sockChannel.bind(server).remove(). socket. Selector selector=Selector. PrintWriter pw=new PrintWriter(new BufferedOutputStream(connection.register(selector. if(selKey.open().getOutputStream()).socket().flush(). .next().selectedKeys().isAcceptable()) { ServerSocketChannel selChannel=(ServerSocketChannel)selKey.accept(). InputStreamReader isr=new InputStreamReader(connection. pw.iterator().InetSocketAddress server=new InetSocketAddress("localhost".79).hasNext()) { SelectionKey selKey=(SelectionKey)it.

close(). pw). if(inLine. pw. connection.close().flush(). String inLine=is.length()>0) { outLine=inLine. pw. } } } } } .readLine(). } readPlan(outLine.String outLine=null. is.close().

java E:\EX3>java New E:\EX3>javac Main.java E:\EX3>java Main NIO finger server .SAMPLE INPUT/OUTPUT: E:\EX3>javac New.

A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained.com". int ttl.Ex. otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host. No. If a literal IP address is supplied. . The host name can either be a machine name. but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. Best effort is made by the implementation to try to reach the host.the specified host. Parameters: host . only the validity of the address format is checked. isReachable public boolean isReachable(NetworkInterface netif. int timeout) throws IOException Test whether that address is reachable. such as "java.sun. 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. Date: Implementation of ping programming Aim To implement the ping programming using java program Theory Inetaddress This class represents an Internet Protocol (IP) address. A negative value for the ttl will result in an IllegalArgumentException being thrown. getByName public static InetAddress getByName(String host) throws UnknownHostException Determines the IP address of a host. or a textual representation of its IP address. given the host's name. or null. 4. Returns: an IP address for the given host name.

the NetworkInterface through which the test will be done.the maximum numbers of hops to try or 0 for the default timeout . the host is deemed unreachable. If the operation times out before getting an answer. indicates the maximum amount of time the try should take. .the time. before the call aborts Returns: a Boolean indicating if the address is reachable. in milliseconds. A negative value will result in an IllegalArgumentException being thrown. in milliseconds. Parameters: netif .The timeout value. or null for any interface ttl .

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

in)). senddata =sentence. clisock.net. DatagramPacket recpack=new DatagramPacket(receivedata.readLine().println("From Server : "+ msentence).*.length.senddata.9876). System. DatagramPacket sendpack=new DatagramPacket(senddata. } } . clisock. String sentence=inFromUser. import java.out.*.close(). byte[] receivedata=new byte[1024]. String msentence=new String(recpack.receive(recpack).length).IPA.getData()).receivedata. byte[] senddata=new byte[1024].getBytes().send(sendpack).getByName("GFL-335"). class UDPClient { public static void main(String args[])throws IOException { BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.SOURCE CODE FOR CLIENT: import java. clisock. InetAddress IPA=InetAddress. DatagramSocket clisock=new DatagramSocket().io.

getAddress(). String csentence=sentence.receivedata.length). String sentence=new String(recpack.port).length.println("Received : "+ sentence).out.getBytes(). int port=recpack.*. import java. class UDPServer { public static void main(String args[])throws IOException { DatagramSocket sersock=new DatagramSocket(9876). byte[] receivedata=new byte[1024].toUpperCase().SOURCE CODE FOR SERVER: import java.io.getData()). } .send(sendpack). senddata =csentence. System.net. byte[] senddata=new byte[1024]. InetAddress IPA=recpack.receive(recpack).*. DatagramPacket sendpack=new DatagramPacket(senddata. sersock. sersock.IPA.getPort(). while(true) { DatagramPacket recpack=new DatagramPacket(receivedata.senddata.

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

and lines of data. . Each packet sent or received on a datagram socket is individually addressed and routed. and may arrive in any order. A datagram socket is the sending or receiving point for a packet delivery service. BufferedReader class The BufferedReader class is used for fast reading operations of texts from a characterinput stream. arrays. The readLine() method of the BufferedReader class can be used to get the next line of characters from a file.Ex. It can be used to read single characters. Multiple packets sent from one machine to another may be routed differently. The size of buffer may or may not be specified. 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. and the skip(long n) method can be used to skip n number of characters. 6. No.

println("End of sending").*. public class EC { public static void main(String args[])throws IOException { byte[] buff=new byte[1024]. pac=new DatagramPacket(buff1. import java.getBytes().length. buff=s.out. System.getData()).getBytes(). soc.out. soc. String s="From client-Hello Server". .SOURCE CODE FOR CLIENT: import java.lang. System. buff1=s. String msg=new String(pac.println(msg).*.buff1.length).send(pac).net. DatagramSocket soc=new DatagramSocket(9999).buff. import java.a. byte[] buff1=new byte[1024].*. DatagramPacket pac=new DatagramPacket(buff.receive(pac).8888).io.getByName("Gfl-335"). InetAddress a=InetAddress.

out.out. import java.io.receive(pac). System.*. String msg=new String(pac.System. soc.getData()).buff.*. } } SOURCE CODE FOR SERVER: import java. DatagramPacket pac=new DatagramPacket(buff.println("server started").*. . System.lang.println(msg). public class ES { public static void main(String args[])throws IOException { byte[] buff=new byte[512].out. System. DatagramSocket soc=new DatagramSocket(8888). import java.println("End of programming").length ).println("End of reception").out.net.

buff1=s.port).length.buff1. byte[] buff1=new byte[512].send(pac).a. pac=new DatagramPacket(buff.println("End of sending"). int port=pac.getPort(). InetAddress a=pac.String s="From Server-Hello client". System.getBytes().out. soc.getAddress(). } } .

java E:\EX6>java EC End of sending From client-Hello Server End of programming .java E:\EX6>java ES server started From client-Hello Server End of reception End of sending E:\EX6>javac EC.SAMPLE INPUT/OUTPUT: E:\EX6>javac ES.

Multiple packets sent from one machine to another may be routed differently. The readLine() method of the BufferedReader class can be used to get the next line of characters from a file. Theory DatagramSocket public class DatagramSocket extends Object implements Closeable This class represents a socket for sending and receiving datagram packets. TCP enables two hosts to establish a connection and exchange streams of data. No. TCP guarantees delivery of data and also guarantees that packets will be delivered in the same order in which they were sent. 7. Date: Implementation of Client Server Communication Using TCP Aim To implement Client Server Communication using TCP through Java programming. The size of buffer may or may not be specified. and may arrive in any order. arrays. TCP TCP is one of the main protocols in TCP/IP networks. BufferedReader class The BufferedReader class is used for fast reading operations of texts from a characterinput stream. . and the skip(long n) method can be used to skip n number of characters. A datagram socket is the sending or receiving point for a packet delivery service. Whereas the IP protocol deals only with packets. and lines of data. It can be used to read single characters.Ex. Each packet sent or received on a datagram socket is individually addressed and routed.

println("\n").*. class CliTCP { public static void main(String args[]) { try { Socket skt=new Socket("Gfl-335".io.readLine()).println(in.println("Received string:").lang. System.SOURCE CODE FOR CLIENT: import java. in.getInputStream())).out. BufferedReader in=new BufferedReader(new InputStreamReader(skt.1234).out.net.out. System. import java.ready()) { } System.*. .close(). import java.println("Whoops! It didn't work! \n").out. } catch(Exception e) { System. while(!in.*.

out.out.true). import java.lang.println("Server has connected! \n"). . try { ServerSocket s=new ServerSocket(1234).println("Sending string: \n "+data+"\n"). import java.*.getOutputStream().*. Socket skt=s.} } } SOURCE CODE FOR SERVER import java.*. PrintWriter out=new PrintWriter(skt.io. System. System.net. class SerTCP { public static void main(String args[]) { String data="Welcome".accept().

print(data).println("Whoops! It didn't work! \n"). skt.close(). out.out. } catch(Exception e) { System. } } } . s.close().out.close().

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 .

arrays. No. 8. The readLine() method of the BufferedReader class can be used to get the next line of characters from a file.Ex. These fields are not public. . public byte[] getAddress() and public String getHostAddress() BufferedReader class The BufferedReader class is used for fast reading operations of texts from a characterinput stream. The Class represents an Internet address as Two fields: 1.Address(an int)= The 32 bit IP address. An instance of an InetAddress consists of an IP address and possibly corresponding hostname. and the skip(long n) method can be used to skip n number of characters. It can be used to read single characters.2. Theory Inet Address public class InetAddress extends Object implements Serializable It is a class in Java which represents an Internet Protocol (IP) address.Host name (The String)=Contain the name of the Host. Date: Implementation of Client server Application for chat Aim To write a java program to implement client server application for chat. The size of buffer may or may not be specified. so we can’t Access them directly. but it has 3 static methods that returns suitably initialized InetAddress Objects namely Public String getHostName() . and lines of data. There is not public constructor in InetAddress class.

lang. import java. import java.*.getOutputStream())). PrintWriter out. BufferedReader d. } .String. String name. out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.*. in=new BufferedReader(new InputStreamReader(soc. BufferedReader in.*.SOURCE CODE FOR CLASS CHAT: import java.io. ServerSocket s. class chat extends Thread { Socket soc.getInputStream())). start().in)). d=new BufferedReader(new InputStreamReader(System.true). InetAddress addr.net. public chat(Socket s)throws IOException { soc= s.

println("Chat sessions begins."). System.println("Message : ").println("Message:").public void run() { String str. name=str. } } catch(IOException e) {} . str=in.out.println(str). addr=soc. out. str=d.println(name+":>"+str). if(str.readLine().equalsIgnoreCase("end")) break. try { out. str=in.readLine(). str=d.out.readLine().println("Server: Your name please : "). while(true) { out.getInetAddress().readLine(). System. System.out..

public static void main(String args[])throws IOException { try { InetAddress a=InetAddress. } } } SOURCE CODE FOR CHAT CLIENT: import java. BufferedReader d=new BufferedReader(new InputStreamReader(System.0202).*.*.io.catch(NullPointerException e) { System. .in)). import java.out.println(name+" quit chat"). soc=new Socket(a.getLocalHost(). class chatclient { public static Socket soc.net.

PrintWriter out=new PrintWriter(new BufferedWriter(new BufferedWriter(new OutputStreamWriter(soc. if(s. while(true) { out.println("Message : ").readLine().getOutputStream()))).readLine(). System.close().readLine().readLine().equalsIgnoreCase("Chat is closing")) break. System. s=d.println(s).BufferedReader in=new BufferedReader(new InputStreamReader(soc. . } } finally { soc.readLine().out.getInputStream())). s=in. System.out.out. s=in.equalsIgnoreCase("end")) break. if(s.println(s). System. s=in.true). String s.out.println(s). s=d.println("Server:> "+s).

class chatserver { public static void main(String args[])throws IOException { ServerSocket s=new ServerSocket(0202).*. try { while(true) { Socket soc=s. import java.accept().*.net. try { new chat(soc).} } } SOURCE CODE FOR CHAT SERVER: import java. .io.

} } } .close().close().} catch(IOException e) { soc. } } } finally { s.

java E:\EX8>java chatserver Message : Hi Client. Server : Your name please : BE IT Server:> Hi Client. E:\EX8>javac chatclient.SAMPLE INPUT/OUTPUT: E:\EX8>javac chatserver. how are you? Message : I am fine.. how are you? BE IT:> I am fine.java E:\EX8>java chatclient Chat sessions begins. .

Typical uses include the updating of mobile personnel from a home office and the periodic issuance of online newsletters. 9. When the socket is created the DatagramSocket.port to use . Theory Multicast Multicast is communication between a single sender and multiple receivers on a network.setReuseAddress(boolean) method is called to enable the SO_REUSEADDR socket option.if an I/O exception occurs while creating the MulticastSocket SecurityException . MulticastSocket public MulticastSocket() throws IOException Create a multicast socket. its checkListen method is first called with the port argument as its argument to ensure the operation is allowed. If there is a security manager. its checkListen method is first called with 0 as its argument to ensure the operation is allowed. Together with anycast and unicast. Date: Implementation of multicast Aim To write a java program for multicast implementation. This could result in a SecurityException. public MulticastSocket(int port) throws IOException Create a multicast socket and bind it to a specific port. Parameters: port . This could result in a SecurityException. multicast is one of the packet types in the Internet Protocol Version 6 (IPv6). Throws: IOException .Ex.if a security manager exists and its checkListen method doesn't allow the operation. No. If there is a security manager.

System.send(pack). public class msource { public static void main(String args[]) { try { DatagramSocket s=new DatagramSocket().close(). s.println("Enter the text to send : ").out. import java.getLocalHost(). } } . InetAddress test=InetAddress.*.in. s.net.16900). byte[] smsg=new byte[100].SOURCE CODE FOR MULTICAST SOURCE: import java.io.*.out. int len=System.len.test.read(smsg). } catch(Exception err) { System.println(err). DatagramPacket pack=new DatagramPacket(smsg.

getData()).io.0.0. mul.getByName("224. String message.net.smsg.joinGroup(InetAddress.*.} SOURCE CODE FOR MULTICAST CLIENT: import java.1")). message=new String(pack.length). import java. .*. public class mulcli { public static void main(String args[]) { try { MulticastSocket mul=new MulticastSocket(16900).receive(pack). DatagramPacket pack=new DatagramPacket(smsg. do { byte[] smsg=new byte[100]. mul.

System. mul.getAddress()+" : "+message).out.println(pack.close(). } catch(Exception e) { System. } } } .println(e).out. } while(!message.equals("close")).

SAMPLE INPUT/OUTPUT: E:\EX9>javac msource.java E:\EX9>java msource Enter the text to send : Information Technology E:\EX9>javac mulcli.java E:\EX9>java mulcli /10.11 : Information Technology .1.60.

ObjectInputStream public class ObjectInputStream extends InputStream implements ObjectInput. Persistent storage of objects can be accomplished by using a file for the stream. Other uses . ObjectInputStream is used to recover those objects previously serialized. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written. the values of the object's fields and arrays.io. including Strings and arrays.Serializable interface can be written to streams. No. Any object. and the closure of any other objects referenced from the initial objects.Ex. The class of each serializable object is encoded including the class name and signature of the class. Only objects that support the java. If the stream is a network socket stream. ObjectStreamConstants An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. The method writeObject is used to write an object to the stream. is written with writeObject. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectStreamConstants An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. the objects can be reconstituted on another host or in another process. 10. Date: Client server Communication using object stream Aim To write a java program to perform Client server Communication using object stream Theory ObjectOutputStream public class ObjectOutputStream extends OutputStream implements ObjectOutput. Multiple objects or primitives can be written to the stream.

. strings and arrays are objects and are treated as objects during serialization.Externalizable interface can be read from streams. The method readObject is used to read an object from the stream. Only objects that support the java.io.io.include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system. Classes are loaded as required using the standard mechanisms. Primitive data types can be read from the stream using the appropriate method on DataInput. In Java. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Java's safe casting should be used to get the desired type. When read they need to be cast to the expected type.Serializable or java.

} catch(Exception err) { System.SOURCE CODE FOR OBJECT SENDER: import java.close().writeObject(newMsg).writeObject(newMsg).*. String newMsg=new String("This is test"). oos. } } } . s.*.out. ObjectOutputStream oos=new ObjectOutputStream(s. public class objectsender { public static void main(String args[]) { try { Socket s=new Socket("localhost". oos.9999). import java.println(err).io.getOutputStream()).net.

Socket s=ss. public class objectreceiver { public static void main(String args[]) { try { ServerSocket ss=new ServerSocket(9999). } catch(Exception err) { System.out. } } } .getInputStream()).readObject().SOURCE CODE FOR OBJECT RECEIVER: import java.*. s. String newMsg=(String)ois.out.accept().println(newMsg). System.net.*. ObjectInputStream ois=new ObjectInputStream(s. import java.io.close().println(err).

java E:\EX10>java objectsender .SAMPLE INPUT/OUTPUT: E:\EX10>javac objectreceiver.java E:\EX10>java objectreceiver This is test E:\EX10>javac objectsender.

The goal of InputStream and OutputStream is to abstract different ways to input and output: whether the stream is a file. To demonstrate how byte streams work. OutputStream is used for many things that you write to. .) InputStream is used for many things that you read from. we'll focus on the file I/O byte streams. All byte stream classes are descended from InputStream and OutputStream. or the screen shouldn't matter. 11. All that matters is that you receive information from the stream (or send information into that stream. No. they differ mainly in the way they are constructed. Other kinds of byte streams are used in much the same way. FileInputStream and FileOutputStream. a web page. There are many byte stream classes. Date: Client Server Communication using byte stream Aim To write a java program to perform client server communication using byte stream. Theory Byte Streams Programs use byte streams to perform input and output of 8-bit bytes.Ex.

} .getInputStream(). import java.*. InputStream is=c.getOutputStream(). OutputStream os=c. public class ses { public static void main(String args[]) { try { ServerSocket s=new ServerSocket(9999). while(true) { Socket c=s.accept().net. String str. str=new String(line). is.SOURCE CODE FOR SERVER: import java.read(line). do { byte[] line=new byte[100]. os.io.write(line).*.

c. } } catch(Exception err) { System.close(). } } } SOURCE CODE FOR CLIENT: import java.equals("Bye")).out.trim(). import java.io. public class sec { public static void main(String args[]) { try { .*.while(!str.net.println(err).*.

do { byte[] line=new byte[100].close().out. str=new String(line). OutputStream os=s.trim()).in.println(str. } catch(Exception err) { System.read(line).write(line). s.trim().Socket s=new Socket("localhost". } while(!str.getInputStream().println(err). InputStream is=s.read(line). System.9999). os.equals("Bye")).getOutputStream(). is.out. } } } . String str. System.

java E:\EX11>java sec BE Final Year BE Final Year Information Technology Information Technology Bye Bye E:\EX11> .java E:\EX11>java ses E:\EX11>javac sec.SAMPLE INPUT/OUTPUT: E:\EX11>javac ses.

When the message is received. an error is detected. Date: Aim Implementation of CRC To implement of CRC using java program Theory CRC Short for cyclic redundancy check. a common technique for detecting data transmission errors.12. If the numbers do not match. the remainder number is appended onto and sent with the message. the computer recalculates the remainder and compares it to the transmitted remainder.Ex. No. . Transmitted messages are divided into predetermined lengths that are divided by a fixed divisor. According to the calculation.

println("Enter the generated code : ").io.*. int lg=ag.println("Enter the data bits to be transmitted : ").length()-1. int i=0.toCharArray().length.i++) { while(i<(len-1)&&am[i]=='0') .in). for(.util. System.x++) m=m+0. int len=am. char am[]=m. for(int x=0.x<g. String g=in.i<len. class crc { public static void main(String args[])throws IOException { DataInputStream in=new DataInputStream(System.out.readLine(). System.SOURCE CODE: import java.out.length.*. import java. String md=m.toCharArray(). char ag[]=g. String m=in.readLine().

i++.j<lg. } int y=0. while(y<(len-1)&&am[y]=='0') { y++. } else i=len. } } i=0. } else { am[i]='1'.{ i++. } if(i<(len-lg+1)) { for(int j=0. .j++) { if(am[i]==ag[j]) { am[i]='0'.

out.out. String r=md. if(r. } } . else System.out.y<len.} for(. System. System.y++) md=md+am[y].equals(md)) System.println("The frame received : " + md).println("The transmitted frame is incorrect").println("The transmitted frame is correct").println("The transmitted frame is : ").out.println(md). System.out.

java E:\EX12>java crc Enter the data bits to be transmitted : 1110001 Enter the generated code : 1101 The transmitted frame is : 111000110 The frame received : 111000110 The transmitted frame is correct .SAMPLE INPUT/OUTPUT: E:\EX12>javac crc.

Ex. Communications are completed by the sending of messages (functions. signals and data packets) to recipients. 13. Message passing is a form of communication used in parallel programming and object-oriented programming. Theory Message Passing It is a type of communication between processes. . No. Date: Message passing using Message Window Aim To write a java program to perform message passing using message window.

net.*.*. import java. import java.awt.intValue()+")").event.Runnable { public MessageWindow() { try { socket=new DatagramSocket().*. import java. public class MessageWindow extends Frame implements ActionListener. setTitle("Messenger(local port="+port.exit(0).SOURCE CODE: import java. } catch(Exception err) {} addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.awt.io. } .*.getLocalPort()). Integer port=new Integer(socket.

addActionListener(this). add(msg). p.RIGHT)).RIGHT)). Button b=new Button("Send!"). setBackground(Color.add(new Label("Port:". setLayout(new BorderLayout()). p.CENTER)).300).Label.getBytes(). . add(p.add(hostname).add(new Label("Host name:".add(portnum). Panel p=new Panel(new FlowLayout(FlowLayout.getText(). p."North"). } public void actionPerformed(ActionEvent event) { if(event. b. Thread t=new Thread(this).getActionCommand().equals("Send!")) try { byte[] data=msg.add(b).start().Label. setSize(600. p.}).lightGray). t. p.

getText()).data. socket. socket.show(). Integer port=new Integer(portnum. Message mwr=new Message(socket.port.getText()).receive(pckt).pckt).length. } catch(Exception err) {} } public void run() { try { while(true) { byte[] data=new byte[2048].InetAddress addr=InetAddress.data.send(pckt).getByName(hostname.getData()). DatagramPacket pckt=new DatagramPacket(data.addr. msg. String mdata=new String(pckt. } } catch(Exception err) {} .setText(mdata).intValue()).length). DatagramPacket pckt=new DatagramPacket(data. mwr.

getHostAddress().getPort()). private TextField hostname=new TextField(10).DatagramPacket pckt) { socket=sock. } class Message extends Frame implements ActionListener { public Message(DatagramSocket sock.intValue()+")"). setTitle("Message from "+hostname+"("+addr+":"+port. try { String hostname=pckt. } private DatagramSocket socket.show().getAddress(). mw. packet=pckt. private TextArea msg=new TextArea().getHostName().getAddress(). String addr=pckt. Integer port=new Integer(pckt. private TextField portnum=new TextField(4). } .} public static void main(String args[]) { MessageWindow mw=new MessageWindow().

msg. . Panel p=new Panel(new FlowLayout(FlowLayout. p. setBackground(new Color(225. p.add(b).addActionListener(this).add(b). b. add(new Label("Edit message and press 'reply!'").addActionListener(this). setLayout(new BorderLayout()).catch(Exception err) {} addWindowListener(new WindowAdapter() { public void WindowClosing(WindowEvent e) { System. add(msg. b.225. } }). b=new Button("close"). Button b=new Button("Reply!"). String data=new String(pckt.CENTER)).getData()).225)).200). setSize(250.exit(0)."Center")."North").setText(data).

int port=packet.getPort().equals("Reply!")) { try { InetAddress addrs=packet."South").port). private TextArea msg=new TextArea().getAddress(). socket.addrs. } private DatagramPacket packet.msg.getActionCommand().getText(). DatagramPacket spacket=new DatagramPacket(msg.getBytes().add(p.getBytes().send(spacket). } public void actionPerformed(ActionEvent event) { if(event.length.getText(). } catch(Exception err) {} } dispose(). } . private DatagramSocket socket.

Date: Message passing using Group Window Aim To write a java program for message passing using group window. Theory Message Passing It is a type of communication between processes.Ex. . Communications are completed by the sending of messages (functions. No. signals and data packets) to recipients. Message passing is a form of communication used in parallel programming and object-oriented programming. 14.

Integer port=new Integer(socket. import java.getLocalPort()).SOURCE CODE: import java.net.exit(0).io. import java.Runnable { public MessageWindow() { try { socket=new DatagramSocket().*. } catch(Exception err) {} addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.intValue()+")").awt.*. } . setTitle("Messenger(local port="+port.event. import java.*.awt. public class MessageWindow extends Frame implements ActionListener.*.

Thread t=new Thread(this). } public void actionPerformed(ActionEvent event) { if(event. add(p.RIGHT)). Button b=new Button("Send!").add(b)."North"). b.Label.getBytes(). setSize(600. p.addActionListener(this).start().equals("Send!")) try { byte[] data=msg.getActionCommand().getText(). p.Label.}).RIGHT)). setLayout(new BorderLayout()). add(msg).300).add(new Label("Port:".add(portnum). p. p.add(new Label("Host name:".lightGray).CENTER)). p. .add(hostname). t. Panel p=new Panel(new FlowLayout(FlowLayout. setBackground(Color.

} } catch(Exception err) {} . socket. socket.getText()). DatagramPacket pckt=new DatagramPacket(data. } catch(Exception err) {} } public void run() { try { while(true) { byte[] data=new byte[2048].receive(pckt).getByName(hostname.show().pckt).port. msg. Message m=new Message(socket.data.send(pckt). Integer port=new Integer(portnum.length.InetAddress addr=InetAddress.getData()). DatagramPacket pckt=new DatagramPacket(data.addr.intValue()).setText(mdata). m.getText()).data.length). String mdata = new String(pckt.

getPort()).getHostAddress(). setTitle("Message from "+hostname+"("+addr+":"+port. private TextArea msg=new TextArea(). String addr=pckt. packet=pckt.intValue()+")").} public static void main(String args[]) { MessageWindow mw=new MessageWindow(). } private DatagramSocket socket. private TextField portnum=new TextField(4).getHostName().getAddress().show().getAddress().DatagramPacket pckt) { socket=sock. private TextField hostname=new TextField(10). mw. try { String hostname=pckt. . } class Message extends Frame implements ActionListener { public Message(DatagramSocket sock. Integer port=new Integer(pckt.

Panel p=new Panel(new FlowLayout(FlowLayout."North"). b.setText(data).225.addActionListener(this). msg. b=new Button("close").add(b).addActionListener(this). add(new Label("Edit message and press 'reply!'"). String data=new String(pckt. } }). add(msg. Button b=new Button("Reply!"). setSize(250.200). .} catch(Exception err) {} addWindowListener(new WindowAdapter() { public void WindowClosing(WindowEvent e) { System.225)). setBackground(new Color(225."Center"). setLayout(new BorderLayout()). p. b.exit(0).CENTER)).getData()).

} private DatagramPacket packet.p. add(p. } .getActionCommand().add(b).getBytes())."South"). socket. private TextArea msg=new TextArea().equals("Reply!")) { try { packet.getText(). } catch(Exception err) {} } dispose().send(packet). private DatagramSocket socket.setData(msg. } public void actionPerformed(ActionEvent event) { if(event.

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. For reading streams of raw bytes. To specify these values yourself. consider using a FileInputStream. construct an InputStreamReader on a FileInputStream. 15. . Date: Implementation of Online test for a Single Client Aim To implement the online test for a single client using java program Theory FileReader public class FileReader extends InputStreamReader Convenience class for reading character files.Ex. No. FileReader is meant for reading streams of characters.

in). class OnlineTestClient { public static void main(String args[])throws IOException { InetAddress a=InetAddress.*.println(d.println(in. } System.io.getOutputStream()).*.readLine()).readLine()).true). System. DataInputStream d=new DataInputStream(System.getLocalHost().readLine()). import java.println(in. out.SOURCE CODE FOR CLIENT: import java.equalsIgnoreCase("test session over")) { System.getInputStream())).println(p).*. PrintWriter out=new PrintWriter(new OutputStreamWriter(soc. String p.6789).out. import java.readLine()).lang. try { BufferedReader in=new BufferedReader(new InputStreamReader(soc. . while(!(p=in. Socket soc=new Socket(a.out.out.net.

lang. import java. class OnlineTestServer { public static void main(String args[])throws IOException { ServerSocket s=new ServerSocket(6789). int nullSpaceRead.close().io.net.} finally { soc. } } } SOURCE CODE FOR SERVER: import java.*. try . Socket soc=s.accept().*. import java.*.

println("Here is your Question").txt").getOutputStream()).println("Error in reading"). s. if((in.println("You have scored "+(r*10)+" points").close().readLine()).out.println(in.readLine()).print("Closing").out.{ FileReader f=new FileReader("E:\\question. out. } finally { System.readLine())) r++.equalsIgnoreCase(b. int r=0. } out. } catch(IOException e) { System. out. BufferedReader in=new BufferedReader(f). out.read())!=-1) { nullSpaceRead = in. PrintWriter out=new PrintWriter(new OutputStreamWriter(soc.read().getInputStream())).println(in. BufferedReader b=new BufferedReader(new InputStreamReader(soc.true).readLine()). while((in. .

txt: Note: The numbering and space left should be as below without any changes.} } } CONTENTS TO BE ON E:\question. g Private . you must declare the data member in the _____ section of the class. which have a single name followed by an index is called e Array 6) If a shift register can be operated in all possible ways then it is called as ______ f Universal 7) To hide a data member from the program. 1) Translator for low level programming language were termed as a Assembler 2) Shell is the exclusive feature of b Unix 3) The statement which is used to terminate the control from the loop is c Break 4) Which feature in OOP allows reusing code? d Inheritance 5) Set of values of the same type.

java E:\EX15>java OnlineTestServer E:\EX5>javac OnlineTestClient.8) The number of structures than can be declared in a single statement is h Unlimited 9) Which technology is used in optical disks? i Laser 10) What is IDE? j Integrated Development Environment test session over SAMPLE INPUT/OUTPUT: E:\EX15>javac OnlineTestServer.java E:\EX5>java OnlineTestClient .

you must declare the data member in the _____ section of the class.Here is your Question 1) Translator for low level programming language were termed as assembler 2) Shell is the exclusive feature of nix 3) The statement which is used to terminate the control from the loop is break 4) Which feature in OOP allows reusing code? inheritance 5) Set of values of the same type. private 8) The number of structures than can be declared in a single statement is unlimited 9) Which technology is used in optical disks? mechanical 10) What is IDE? integrated development environment You have scored 70 points . which have a single name followed by an index is called array 6) If a shift register can be operated in all possible ways then it is called as ______ cache 7) To hide a data member from the program.