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.1.11 .SAMPLE INPUT/OUTPUT: E:\EX1>javac getOwnIP.java E:\EX1>java getOwnIP IP of this system=10.

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

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

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

This is usually assigned by the system. listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. 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. the server accepts the connection. No. On the client side. 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. a socket is successfully created and the client can use the socket to communicate with the server. To make a connection request. if the connection is accepted. The server just waits. a server runs on a specific computer and has a socket that is bound to a specific port number. If everything goes well. 2. The client and server can now communicate by writing to or reading from their sockets.Ex. Definition: . the client tries to rendezvous with the server on the server's machine and port. Date: Implementation of port scanner Aim To implement the port scanner using java program Theory Socket Normally. Upon acceptance. 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 includes the ServerSocket class. An endpoint is a combination of an IP address and a port number. hiding the details of any particular system from your Java program. Otherwise a "plain" socket is created. By using the java. port . Socket. int port) throws IOException Creates a stream socket and connects it to the specified port number at the specified IP address. Additionally. that factory's createSocketImpl method is called to create the actual socket implementation. .net package in the Java platform provides a class. 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. If there is a security manager. Socket constructor public Socket(InetAddress address. This could result in a SecurityException. java. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.A socket is one endpoint of a two-way communication link between two programs running on the network. its checkConnect method is called with the host address and port as its arguments. your Java programs can communicate over the network in a platformindependent fashion.Socket class instead of relying on native code. that implements one side of a two-way connection between your Java program and another program on the network.net. That way you can have multiple connections between your host and the server. This lesson shows you how to use the Socket and ServerSocket classes. Socket close method public void close() throws IOException Closes this socket. Parameters: address . which implements a socket that servers can use to listen for and accept connections to clients. The Socket class sits on top of a platform-dependent implementation. The java. If the application has specified a socket factory.the port number.the IP address. Every TCP connection can be uniquely identified by its two endpoints.

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

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

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

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

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

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

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

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

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

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

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

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

or null for any interface ttl .the time. . in milliseconds.The timeout value. A negative value will result in an IllegalArgumentException being thrown. If the operation times out before getting an answer.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. in milliseconds. Parameters: netif . the host is deemed unreachable. before the call aborts Returns: a Boolean indicating if the address is reachable.

SOURCE CODE:

import java.net.*;
import java.io.*;

public class Ping
{
public static void main(String args[])
{
System.out.println("Pinging status");
String ipa="GFL-335";
try
{
InetAddress IPA=InetAddress.getByName("Gfl-335");
System.out.println("Sending ping request to " +ipa);
boolean status=IPA.isReachable(50000);
if(status)
{
System.out.println("Status : Host is reachable");
}
else
{
System.out.println("Status : Host is not reachable");
}
}

catch(IOException e)
{
System.out.println("Host does not exist");
}
}
}

SAMPLE INPUT/OUTPUT:

E:\EX4>javac Ping.java

E:\EX4>java Ping
Pinging status
Sending ping request to GFL-335
Status : Host is reachable

Ex. No. 5.
Date:

Implementation of peer to peer communication using UDP
Aim
To implement the peer to peer communication through UDP using java program
Theory

Peer to peer communication
P2P, P-to-P and P2P communications, peer-to-peer communication refers to the
transmission between two peer computers over a network. P2P became widely known by
computer users as they began sharing MP3s and other files over P2P networks
UDP
UDP (User Datagram Protocol) is a communications protocol that offers a limited
amount of service when messages are exchanged between computers in a network that uses the
Internet Protocol (IP).

UDP Datagram
UDP network traffic is organized in the form of datagrams . A datagram comprises one
message unit. The first eight (8) bytes of a datagram contain header information and the
remaining bytes contain message data.
A UDP datagram header consists of four (4) fields of two bytes each:



source port number
destination port number
datagram size
checksum

UDP port numbers allow different applications to maintain their own channels for data
similar to TCP. UDP port headers are two bytes long; therefore, valid UDP port numbers range
from 0 to 65535.

The UDP datagram size is a count of the total number of bytes contained in header and data
sections. As the header length is a fixed size, this field effectively tracks the length of the
variable-sized data portion (sometimes called payload). The size of datagrams varies depending
on the operating environment but has a maximum of 65535 bytes.
UDP checksums protect message data from tampering. The checksum value represents an
encoding of the datagram data calculated first by the sender and later by the receiver. Should an
individual datagram be tampered with or get corrupted during transmission, the UDP protocol
detects a checksum calculation mismatch. In UDP, checksumming is optional as opposed to TCP
where checksums are mandatory.

Datagram Socket
public class DatagramSocket
extends Object
implements Closeable
This class represents a socket for sending and receiving datagram packets.
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
BufferedReader class
The BufferedReader class is used for fast reading operations of texts from a 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.

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

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

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

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

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

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

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

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

TCP enables two hosts to establish a connection and exchange streams of data. A datagram socket is the sending or receiving point for a packet delivery service. Date: Implementation of Client Server Communication Using TCP Aim To implement Client Server Communication using TCP through Java programming. TCP TCP is one of the main protocols in TCP/IP networks. 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. Whereas the IP protocol deals only with packets.Ex. and may arrive in any order. Each packet sent or received on a datagram socket is individually addressed and routed. Theory DatagramSocket public class DatagramSocket extends Object implements Closeable This class represents a socket for sending and receiving datagram packets. The size of buffer may or may not be specified. 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. arrays. 7. Multiple packets sent from one machine to another may be routed differently. and the skip(long n) method can be used to skip n number of characters. . No. and lines of data.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Only objects that support the java. Primitive data types can be read from the stream using the appropriate method on DataInput. In Java. The method readObject is used to read an object from the stream.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.Serializable or java.io.Externalizable interface can be read from streams. strings and arrays are objects and are treated as objects during serialization. Java's safe casting should be used to get the desired type. When read they need to be cast to the expected type.io. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. .

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

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

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

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

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

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

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

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.

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

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

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

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

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.

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

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

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

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

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

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

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

Ex. 14. Theory Message Passing It is a type of communication between processes. 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. signals and data packets) to recipients. Communications are completed by the sending of messages (functions. No. .

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

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

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

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

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

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

FileReader is meant for reading streams of characters. . No. consider using a FileInputStream.Ex. 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. 15. 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. construct an InputStreamReader on a FileInputStream. To specify these values yourself.

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

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

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

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

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

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