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

60.java E:\EX1>java getOwnIP IP of this system=10.1.SAMPLE INPUT/OUTPUT: E:\EX1>javac getOwnIP.11 .

b Date: Looking up internet address of Remote host Aim To find the IP address of a remote host using java program Theory 1. or if a scope_id was specified for a global IPv6 address. such as " java. If a literal IP address is supplied. only the validity of the address format is checked. given the host's name. See here for a description of IPv6 scoped addresses. either the form defined in RFC 2732 or the literal IPv6 address format defined in RFC 2373 is accepted.if no IP address for the host could be found. For host specified in literal IPv6 address. Throws: UnknownHostException .if a security manager exists and its checkConnect method doesn't allow the operation . No.Ex. or null.the specified host. getByName public static InetAddress getByName(String host) throws UnknownHostException Determines the IP address of a host. Returns: an IP address for the given host name.com". 1. SecurityException . IPv6 scoped addresses are also supported. Parameters: host . or a textual representation of its IP address. The host name can either be a machine name.sun.

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

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

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

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

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

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

println("Port not in use : "+i). } } } . n=1.if(n!=0) System.out.

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 .

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

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

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

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

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

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

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

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

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

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

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

java E:\EX5>java UDPClient Hi Server From Server : HI SERVER .java E:\EX5>java UDPServer Received : Hi Server E:\EX5>javac UDPClient.} } SAMPLE INPUT/OUTPUT: E:\EX5>javac UDPServer.

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

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

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

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

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.

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

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

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

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

SAMPLE INPUT/OUTPUT: E:\EX7>javac SerTCP.java E:\EX7>java CliTCP Received string: Welcome .java E:\EX7>java SerTCP Server has connected! Sending string: Welcome E:\EX7>javac CliTCP.

Address(an int)= The 32 bit IP address. and the skip(long n) method can be used to skip n number of characters. These fields are not public. It can be used to read single characters. No. and lines of data. There is not public constructor in InetAddress class.Host name (The String)=Contain the name of the Host. so we can’t Access them directly. 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 readLine() method of the BufferedReader class can be used to get the next line of characters from a file.2. arrays.Ex. 8. but it has 3 static methods that returns suitably initialized InetAddress Objects namely Public String getHostName() . . The Class represents an Internet address as Two fields: 1. 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 size of buffer may or may not be specified. Date: Implementation of Client server Application for chat Aim To write a java program to implement client server application for chat.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SAMPLE INPUT/OUTPUT: E:\EX12>javac crc.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 .

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

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

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

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

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

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

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

Date: Message passing using Group Window Aim To write a java program for message passing using group window. 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. 14. No. . Communications are completed by the sending of messages (functions. signals and data packets) to recipients.Ex.

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

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

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

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

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

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

consider using a FileInputStream. construct an InputStreamReader on a FileInputStream.Ex. No. For reading streams of raw bytes. . To specify these values yourself. 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. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. 15. FileReader is meant for reading streams of characters.

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

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

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

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. g Private .txt: Note: The numbering and space left should be as below without any changes.} } } CONTENTS TO BE ON E:\question. 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. you must declare the data member in the _____ section of the class.

java E:\EX5>java 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:\EX15>java OnlineTestServer E:\EX5>javac OnlineTestClient.

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