+ All Categories
Home > Documents > BE-IT-VII SEM - 97708- Network Lab Manual

BE-IT-VII SEM - 97708- Network Lab Manual

Date post: 15-Sep-2015
Category:
Upload: usman-shaik
View: 231 times
Download: 5 times
Share this document with a friend
Description:
hgvfklhgjhkhjjkhjk
Popular Tags:
89
Annamalai University Department of Computer Science and Engineering LAB MANUAL 97708 – NETWORK PROGRAMMING LAB BE(IT) VII Semester In charge: R.Arunkumar
Transcript
  • Annamalai UniversityDepartment of Computer Science and Engineering

    LAB MANUAL

    97708 NETWORK PROGRAMMING LABBE(IT) VII Semester

    In charge: R.Arunkumar

  • CONTENT

    Sl.no. Titles Remarks01 Looking up internet address02 Implementation of port scanner03 Implementation of finger client04 Implementation of ping programming05 Implementation of peer to peer communication using UDP

    06 Implementation of socket program for UDP Echo Client and EchoServer

    07 Implementation of Client Server Communication Using TCP

    08 Implementation of Client server Application for chat09 Java multicast programming10 Client server Communication using object stream11 Client server Communication using byte stream12 Implementation of CRC

    13 Message passing using Message Window14 Message Passing using Group Window15 Implementation of Online test for a Single Client

  • Ex. No. 1.aDate:

    Looking up internet address of local hostAim

    To find the IP address of a local host using java programTheoryInet Address

    public class InetAddressextends Objectimplements Serializable

    It is a class in Java which represents an Internet Protocol (IP) address. An instance of anInetAddress consists of an IP address and possibly corresponding hostname. The Classrepresents an Internet address as Two fields: 1- Host name (The String)=Contain the name of theHost.2- Address(an int)= The 32 bit IP address. These fields are not public, so we cant Accessthem directly. There is not public constructor in InetAddress class, but it has 3 static methodsthat returns suitably initialized InetAddress Objects namely Public String getHostName() , publicbyte[] getAddress() and public String getHostAddress()

    getLocalHost()public static InetAddress getLocalHost()

    throws UnknownHostExceptionReturns the address of the local host. This is achieved by retrieving the name of the host from thesystem, 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 -1as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddressrepresenting the loopback address is returned.Returns:

    the address of the local host.Throws:

    UnknownHostException - if the local host name could not be resolved into an address.

  • SOURCE CODE:

    import java.util.*;import java.lang.*;import java.net.*;

    public class getOwnIP{public static void main(String args[])throws UnknownHostException{try{InetAddress IPO=InetAddress.getLocalHost();System.out.println("IP of this system="+IPO.getHostAddress());}catch(Exception e){System.out.println("Exception caught="+e.getMessage());}}}

  • SAMPLE INPUT/OUTPUT:

    E:\EX1>javac getOwnIP.java

    E:\EX1>java getOwnIPIP of this system=10.1.60.11

  • Ex. No. 1.bDate:

    Looking up internet address of Remote hostAim

    To find the IP address of a remote host using java programTheory1. getByName

    public static InetAddress getByName(String host)throws UnknownHostException

    Determines the IP address of a host, given the host's name.The host name can either be a machine name, such as "java.sun.com", or a textual

    representation of its IP address. If a literal IP address is supplied, only the validity of the addressformat is checked.

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

    host - the specified host, or null.Returns:

    an IP address for the given host name.Throws:

    UnknownHostException - if no IP address for the host could be found, or if a scope_id wasspecified for a global IPv6 address.SecurityException - if a security manager exists and its checkConnect method doesn't allowthe operation

  • SOURCE CODE:

    import java.util.*;import java.lang.*;import java.net.*;

    public class getRemoteIP{public static void main(String args[]){try{InetAddress IPO=InetAddress.getByName(args[0]);System.out.println("IP of this system = " +IPO);}catch(Exception e){System.out.println("Exception caught = "+e.getMessage());}}}

  • SAMPLE INPUT/OUTPUT:

    E:\EX1>javac getRemoteIP.java

    E:\EX1>java getRemoteIPIP of this system = GFL-335/10.1.60.11

  • Ex. No. 2.Date:

    Implementation of port scannerAim

    To implement the port scanner using java programTheorySocketNormally, a server runs on a specific computer and has a socket that is bound to a specific portnumber. The server just waits, listening to the socket for a client to make a connection request.On the client-side: The client knows the hostname of the machine on which the server is runningand the port number on which the server is listening. To make a connection request, the clienttries to rendezvous with the server on the server's machine and port. The client also needs toidentify itself to the server so it binds to a local port number that it will use during thisconnection. This is usually assigned by the system.

    If everything goes well, the server accepts the connection. Upon acceptance, the server gets anew socket bound to the same local port and also has its remote endpoint set to the address andport of the client. It needs a new socket so that it can continue to listen to the original socket forconnection requests while tending to the needs of the connected client.

    On the client side, if the connection is accepted, a socket is successfully created and the clientcan use the socket to communicate with the server.The client and server can now communicate by writing to or reading from their sockets.

    Definition:

  • A socket is one endpoint of a two-way communication link between two programs running onthe network. A socket is bound to a port number so that the TCP layer can identify theapplication that data is destined to be sent to.

    An endpoint is a combination of an IP address and a port number. Every TCP connectioncan be uniquely identified by its two endpoints. That way you can have multiple connectionsbetween your host and the server.

    The java.net package in the Java platform provides a class, Socket, that implements oneside of a two-way connection between your Java program and another program on the network.The Socket class sits on top of a platform-dependent implementation, hiding the details of anyparticular system from your Java program. By using the java.net.Socket class instead of relyingon native code, your Java programs can communicate over the network in a platform-independent fashion.

    Additionally, java.net includes the ServerSocket class, which implements a socket thatservers can use to listen for and accept connections to clients. This lesson shows you how to usethe Socket and ServerSocket classes.

    Socket constructorpublic Socket(InetAddress address, int port) throws IOExceptionCreates a stream socket and connects it to the specified port number at the specified IP address.

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

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

    address - the IP address.port - the port number.

    Socket close methodpublic void close() throws IOExceptionCloses this socket.Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.

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

  • SOURCE CODE:

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

    public class PortScanner{public static void main(String args[]){int startPortRange = 0;int stopPortRange = 0;int n=1;startPortRange = Integer.parseInt(args[0]);stopPortRange = Integer.parseInt(args[1]);for(int i=startPortRange; i

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

    n=1;}}}

  • SAMPLE INPUT/OUTPUT:

    E:\EX2>javac PortScanner.java

    E:\EX2>java PortScanner 132 137Port not in use : 132Port not in use : 133Port not in use : 134Port not use : 135Port not in use : 136Port not in use : 137

    E:\EX2>java PortScanner 442 447Port not in use : 442Port not in use : 443Port not in use : 444Port not use : 445Port not in use : 446Port not in use : 447

  • Ex. No. 3.Date:

    Implementation of finger clientAim

    To implement the finger client using java programTheorySocketSockets provide the communication mechanism between two computers using TCP. A clientprogram creates a socket on its end of the communication and attempts to connect that socket toa server.When the connection is made, the server creates a socket object on its end of the communication.The client and server can now communicate by writing to and reading from the socket.Class Writerpublic abstract class Writer extends Object implements Appendable, Closeable, Flushable

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

    Returns an input stream for this socket.

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

    void close()Closes this socket.

  • SOURCE CODE FOR CLIENT:

    import java.io.BufferedInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Writer;import java.net.Socket;

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

  • if((c>=32 && c
  • import java.util.Iterator;import java.util.Set;

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

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

    BufferedOutputStream(connection.getOutputStream()),false);pw.println("NIO finger server");pw.flush();

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX3>javac New.java

    E:\EX3>java New

    E:\EX3>javac Main.java

    E:\EX3>java MainNIO finger server

  • Ex. No. 4.Date:

    Implementation of ping programmingAim

    To implement the ping programming using java programTheoryInetaddress

    This class represents an Internet Protocol (IP) address.getByNamepublic static InetAddress getByName(String host)

    throws UnknownHostExceptionDetermines the IP address of a host, given the host's name.The host name can either be a machine name, such as "java.sun.com", or a textual representationof its IP address. If a literal IP address is supplied, only the validity of the address format ischecked.Parameters:

    host - the specified host, or null.Returns:

    an IP address for the given host name.

    isReachablepublic boolean isReachable(NetworkInterface netif,

    int ttl,int timeout)throws IOException

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

    The network interface and ttl parameters let the caller specify which network interfacethe test will go through and the maximum number of hops the packets should go through. Anegative value for the ttl will result in an IllegalArgumentException being thrown.

  • The timeout value, in milliseconds, indicates the maximum amount of time the try shouldtake. If the operation times out before getting an answer, the host is deemed unreachable. Anegative value will result in an IllegalArgumentException being thrown.Parameters:

    netif - the NetworkInterface through which the test will be done, or null for any interfacettl - the maximum numbers of hops to try or 0 for the defaulttimeout - the time, in milliseconds, before the call aborts

    Returns:a Boolean indicating if the address is reachable.

  • SOURCE CODE:

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

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

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

    SAMPLE INPUT/OUTPUT:

    E:\EX4>javac Ping.java

    E:\EX4>java PingPinging statusSending ping request to GFL-335Status : Host is reachable

  • Ex. No. 5.Date:

    Implementation of peer to peer communication using UDPAim

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

    Peer to peer communicationP2P, 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 bycomputer users as they began sharing MP3s and other files over P2P networksUDP

    UDP (User Datagram Protocol) is a communications protocol that offers a limitedamount of service when messages are exchanged between computers in a network that uses theInternet Protocol (IP).

    UDP Datagram

    UDP network traffic is organized in the form of datagrams . A datagram comprises onemessage unit. The first eight (8) bytes of a datagram contain header information and theremaining 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 checksumUDP 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 rangefrom 0 to 65535.

  • The UDP datagram size is a count of the total number of bytes contained in header and datasections. As the header length is a fixed size, this field effectively tracks the length of thevariable-sized data portion (sometimes called payload). The size of datagrams varies dependingon the operating environment but has a maximum of 65535 bytes.

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

    Datagram Socketpublic class DatagramSocket

    extends Objectimplements 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. Multiplepackets sent from one machine to another may be routed differently, and may arrive in any order.BufferedReader class

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

  • SOURCE CODE FOR CLIENT:

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

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

  • SOURCE CODE FOR SERVER:

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

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

  • }}

    SAMPLE INPUT/OUTPUT:

    E:\EX5>javac UDPServer.java

    E:\EX5>java UDPServerReceived : Hi Server

    E:\EX5>javac UDPClient.java

    E:\EX5>java UDPClientHi ServerFrom Server : HI SERVER

  • Ex. No. 6.Date:

    Implementation of socket program for UDP Echo Client and Echo ServerAim

    To implement a socket program for UDP Echo Client and Echo Server using javaprogramTheoryDatagramSocketpublic class DatagramSocket

    extends Objectimplements 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. Multiplepackets sent from one machine to another may be routed differently, and may arrive in any order.BufferedReader class

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

  • SOURCE CODE FOR CLIENT:

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

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

  • System.out.println("End of programming");}}

    SOURCE CODE FOR SERVER:

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

    public class ES{public static void main(String args[])throws IOException{byte[] buff=new byte[512];DatagramSocket soc=new DatagramSocket(8888);DatagramPacket pac=new DatagramPacket(buff,buff.length );System.out.println("server started");soc.receive(pac);String msg=new String(pac.getData());System.out.println(msg);System.out.println("End of reception");

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX6>javac ES.java

    E:\EX6>java ESserver startedFrom client-Hello Server

    End of receptionEnd of sending

    E:\EX6>javac EC.java

    E:\EX6>java EC

    End of sendingFrom client-Hello ServerEnd of programming

  • Ex. No. 7.Date:

    Implementation of Client Server Communication Using TCPAim

    To implement Client Server Communication using TCP through Java programming.TheoryDatagramSocketpublic class DatagramSocket

    extends Objectimplements 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. Multiplepackets sent from one machine to another may be routed differently, and may arrive in any order.BufferedReader class

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

    TCPTCP is one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only

    with packets, TCP enables two hosts to establish a connection and exchange streams of data.TCP guarantees delivery of data and also guarantees that packets will be delivered in the sameorder in which they were sent.

  • SOURCE CODE FOR CLIENT:

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

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

  • }}}

    SOURCE CODE FOR SERVER

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

    class SerTCP{public static void main(String args[]){String data="Welcome";try{ServerSocket s=new ServerSocket(1234);Socket skt=s.accept();System.out.println("Server has connected! \n");PrintWriter out=new PrintWriter(skt.getOutputStream(),true);System.out.println("Sending string: \n "+data+"\n");

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX7>javac SerTCP.java

    E:\EX7>java SerTCPServer has connected!

    Sending string:Welcome

    E:\EX7>javac CliTCP.java

    E:\EX7>java CliTCP

    Received string:Welcome

  • Ex. No. 8.Date:

    Implementation of Client server Application for chatAim

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

    public class InetAddressextends Objectimplements Serializable

    It is a class in Java which represents an Internet Protocol (IP) address. An instance of anInetAddress consists of an IP address and possibly corresponding hostname. The Classrepresents an Internet address as Two fields: 1- Host name (The String)=Contain the name of theHost.2- Address(an int)= The 32 bit IP address. These fields are not public, so we cant Accessthem directly. There is not public constructor in InetAddress class, but it has 3 static methodsthat returns suitably initialized InetAddress Objects namely Public String getHostName() , publicbyte[] getAddress() and public String getHostAddress()BufferedReader class

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

  • SOURCE CODE FOR CLASS CHAT:

    import java.io.*;import java.net.*;import java.lang.String.*;

    class chat extends Thread{Socket soc;InetAddress addr;ServerSocket s;BufferedReader d;BufferedReader in;PrintWriter out;String name;public chat(Socket s)throws IOException{soc= s;d=new BufferedReader(new InputStreamReader(System.in));in=new BufferedReader(new InputStreamReader(soc.getInputStream()));out=new PrintWriter(new BufferedWriter(new

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

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

  • catch(NullPointerException e){System.out.println(name+" quit chat");}}}

    SOURCE CODE FOR CHAT CLIENT:

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

    class chatclient{public static Socket soc;public static void main(String args[])throws IOException{try{InetAddress a=InetAddress.getLocalHost();soc=new Socket(a,0202);BufferedReader d=new BufferedReader(new InputStreamReader(System.in));

  • BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()));PrintWriter out=new PrintWriter(new BufferedWriter(new BufferedWriter(new

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

  • }}}

    SOURCE CODE FOR CHAT SERVER:

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

    class chatserver{public static void main(String args[])throws IOException{ServerSocket s=new ServerSocket(0202);try{while(true){Socket soc=s.accept();try{new chat(soc);

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX8>javac chatserver.java

    E:\EX8>java chatserverMessage :Hi Client, how are you?BE IT:> I am fine.

    E:\EX8>javac chatclient.java

    E:\EX8>java chatclientChat sessions begins..Server : Your name please :BE ITServer:> Hi Client, how are you?Message :I am fine.

  • Ex. No. 9.Date:

    Implementation of multicastAim

    To write a java program for multicast implementation.TheoryMulticast

    Multicast is communication between a single sender and multiple receivers on a network.Typical uses include the updating of mobile personnel from a home office and the periodicissuance of online newsletters. Together with anycast and unicast, multicast is one of the packettypes in the Internet Protocol Version 6 (IPv6).MulticastSocketpublic MulticastSocket()

    throws IOExceptionCreate a multicast socket.If there is a security manager, its checkListen method is first called with 0 as its argument toensure the operation is allowed. This could result in a SecurityException.Throws:

    IOException - if an I/O exception occurs while creating the MulticastSocketSecurityException - if a security manager exists and its checkListen method doesn't allowthe operation.

    public MulticastSocket(int port)throws IOException

    Create a multicast socket and bind it to a specific port.If there is a security manager, its checkListen method is first called with the port argument as itsargument to ensure the operation is allowed. This could result in a SecurityException.When the socket is created the DatagramSocket.setReuseAddress(boolean) method is called toenable the SO_REUSEADDR socket option.Parameters:

    port - port to use

  • SOURCE CODE FOR MULTICAST SOURCE:

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

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

  • }SOURCE CODE FOR MULTICAST CLIENT:

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

    public class mulcli{public static void main(String args[]){try{MulticastSocket mul=new MulticastSocket(16900);mul.joinGroup(InetAddress.getByName("224.0.0.1"));String message;do{byte[] smsg=new byte[100];DatagramPacket pack=new DatagramPacket(smsg,smsg.length);mul.receive(pack);message=new String(pack.getData());

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX9>javac msource.java

    E:\EX9>java msourceEnter the text to send :Information Technology

    E:\EX9>javac mulcli.java

    E:\EX9>java mulcli/10.1.60.11 : Information Technology

  • Ex. No. 10.Date:

    Client server Communication using object streamAim

    To write a java program to perform Client server Communication using object streamTheoryObjectOutputStreampublic class ObjectOutputStream

    extends OutputStreamimplements ObjectOutput, ObjectStreamConstants

    An ObjectOutputStream writes primitive data types and graphs of Java objects to anOutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistentstorage of objects can be accomplished by using a file for the stream. If the stream is a networksocket stream, the objects can be reconstituted on another host or in another process.

    Only objects that support the java.io.Serializable interface can be written to streams. Theclass of each serializable object is encoded including the class name and signature of the class,the values of the object's fields and arrays, and the closure of any other objects referenced fromthe initial objects.

    The method writeObject is used to write an object to the stream. Any object, includingStrings and arrays, is written with writeObject. Multiple objects or primitives can be written tothe stream. The objects must be read back from the corresponding ObjectInputstream with thesame types and in the same order as they were written.

    ObjectInputStreampublic class ObjectInputStream

    extends InputStreamimplements ObjectInput, ObjectStreamConstants

    An ObjectInputStream deserializes primitive data and objects previously written using anObjectOutputStream.

    ObjectOutputStream and ObjectInputStream can provide an application with persistentstorage for graphs of objects when used with a FileOutputStream and FileInputStreamrespectively. ObjectInputStream is used to recover those objects previously serialized. Other uses

  • include passing objects between hosts using a socket stream or for marshaling and unmarshalingarguments and parameters in a remote communication system.

    ObjectInputStream ensures that the types of all objects in the graph created from thestream match the classes present in the Java Virtual Machine. Classes are loaded as requiredusing the standard mechanisms.

    Only objects that support the java.io.Serializable or java.io.Externalizable interface canbe read from streams.

    The method readObject is used to read an object from the stream. Java's safe castingshould be used to get the desired type. In Java, strings and arrays are objects and are treated asobjects during serialization. When read they need to be cast to the expected type.Primitive data types can be read from the stream using the appropriate method on DataInput.

  • SOURCE CODE FOR OBJECT SENDER:

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

    public class objectsender{public static void main(String args[]){try{Socket s=new Socket("localhost",9999);ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());String newMsg=new String("This is test");oos.writeObject(newMsg);oos.writeObject(newMsg);s.close();}catch(Exception err){System.out.println(err);}}}

  • SOURCE CODE FOR OBJECT RECEIVER:

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

    public class objectreceiver{public static void main(String args[]){try{ServerSocket ss=new ServerSocket(9999);Socket s=ss.accept();ObjectInputStream ois=new ObjectInputStream(s.getInputStream());String newMsg=(String)ois.readObject();System.out.println(newMsg);s.close();}catch(Exception err){System.out.println(err);}}}

  • SAMPLE INPUT/OUTPUT:

    E:\EX10>javac objectreceiver.java

    E:\EX10>java objectreceiverThis is test

    E:\EX10>javac objectsender.java

    E:\EX10>java objectsender

  • Ex. No. 11.Date:

    Client Server Communication using byte streamAim

    To write a java program to perform client server communication using byte stream.TheoryByte Streams

    Programs use byte streams to perform input and output of 8-bit bytes. All byte streamclasses are descended from InputStream and OutputStream.

    There are many byte stream classes. To demonstrate how byte streams work, we'll focuson the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streamsare used in much the same way; they differ mainly in the way they are constructed.The goal of InputStream and OutputStream is to abstract different ways to input and output:whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is thatyou receive information from the stream (or send information into that stream.)InputStream is used for many things that you read from.OutputStream is used for many things that you write to.

  • SOURCE CODE FOR SERVER:

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

    public class ses{public static void main(String args[]){try{ServerSocket s=new ServerSocket(9999);String str;while(true){Socket c=s.accept();InputStream is=c.getInputStream();OutputStream os=c.getOutputStream();do{byte[] line=new byte[100];is.read(line);os.write(line);str=new String(line);}

  • while(!str.trim().equals("Bye"));c.close();}}catch(Exception err){System.out.println(err);}}}

    SOURCE CODE FOR CLIENT:

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

    public class sec{public static void main(String args[]){try{

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

  • SAMPLE INPUT/OUTPUT:

    E:\EX11>javac ses.java

    E:\EX11>java ses

    E:\EX11>javac sec.java

    E:\EX11>java secBE Final YearBE Final YearInformation TechnologyInformation TechnologyByeBye

    E:\EX11>

  • Ex. No.12.Date:

    Implementation of CRCAim

    To implement of CRC using java programTheoryCRC

    Short for cyclic redundancy check, a common technique for detecting data transmissionerrors. Transmitted messages are divided into predetermined lengths that are divided by a fixeddivisor. According to the calculation, the remainder number is appended onto and sent with themessage. When the message is received, the computer recalculates the remainder and comparesit to the transmitted remainder. If the numbers do not match, an error is detected.

  • SOURCE CODE:

    import java.io.*;import java.util.*;

    class crc{public static void main(String args[])throws IOException{DataInputStream in=new DataInputStream(System.in);System.out.println("Enter the data bits to be transmitted : ");String m=in.readLine();String md=m;System.out.println("Enter the generated code : ");String g=in.readLine();for(int x=0;x

  • {i++;}if(i
  • }for(;y
  • SAMPLE INPUT/OUTPUT:

    E:\EX12>javac crc.java

    E:\EX12>java crcEnter the data bits to be transmitted :1110001Enter the generated code :1101The transmitted frame is :111000110The frame received : 111000110The transmitted frame is correct

  • Ex. No. 13.Date:

    Message passing using Message WindowAim

    To write a java program to perform message passing using message window.TheoryMessage Passing

    It is a type of communication between processes. Message passing is a form ofcommunication used in parallel programming and object-oriented programming.Communications are completed by the sending of messages (functions, signals and data packets)to recipients.

  • SOURCE CODE:

    import java.awt.*;import java.awt.event.*;import java.net.*;import java.io.*;

    public class MessageWindow extends Frame implements ActionListener,Runnable{public MessageWindow(){try{socket=new DatagramSocket();Integer port=new Integer(socket.getLocalPort());setTitle("Messenger(local port="+port.intValue()+")");}catch(Exception err){}addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}

  • });

    setSize(600,300);setBackground(Color.lightGray);setLayout(new BorderLayout());Panel p=new Panel(new FlowLayout(FlowLayout.CENTER));p.add(new Label("Host name:",Label.RIGHT));p.add(hostname);

    p.add(new Label("Port:",Label.RIGHT));p.add(portnum);Button b=new Button("Send!");b.addActionListener(this);p.add(b);add(p,"North");add(msg);Thread t=new Thread(this);t.start();}public void actionPerformed(ActionEvent event){if(event.getActionCommand().equals("Send!"))try{byte[] data=msg.getText().getBytes();

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

  • }public static void main(String args[]){MessageWindow mw=new MessageWindow();mw.show();}private DatagramSocket socket;private TextArea msg=new TextArea();private TextField hostname=new TextField(10);private TextField portnum=new TextField(4);}

    class Message extends Frame implements ActionListener{public Message(DatagramSocket sock,DatagramPacket pckt){socket=sock;packet=pckt;try{String hostname=pckt.getAddress().getHostName();String addr=pckt.getAddress().getHostAddress();Integer port=new Integer(pckt.getPort());setTitle("Message from "+hostname+"("+addr+":"+port.intValue()+")");}

  • catch(Exception err){}

    addWindowListener(new WindowAdapter(){public void WindowClosing(WindowEvent e){System.exit(0);}});

    setSize(250,200);setBackground(new Color(225,225,225));setLayout(new BorderLayout());add(new Label("Edit message and press 'reply!'"),"North");String data=new String(pckt.getData());msg.setText(data);add(msg,"Center");Panel p=new Panel(new FlowLayout(FlowLayout.CENTER));Button b=new Button("Reply!");b.addActionListener(this);p.add(b);b=new Button("close");b.addActionListener(this);p.add(b);

  • add(p,"South");}

    public void actionPerformed(ActionEvent event){if(event.getActionCommand().equals("Reply!")){try{InetAddress addrs=packet.getAddress();int port=packet.getPort();DatagramPacket spacket=new

    DatagramPacket(msg.getText().getBytes(),msg.getText().getBytes().length,addrs,port);socket.send(spacket);}catch(Exception err){}}dispose();}private DatagramPacket packet;private DatagramSocket socket;private TextArea msg=new TextArea();}

  • Ex. No. 14.Date:

    Message passing using Group WindowAim

    To write a java program for message passing using group window.TheoryMessage Passing

    It is a type of communication between processes. Message passing is a form ofcommunication used in parallel programming and object-oriented programming.Communications are completed by the sending of messages (functions, signals and data packets)to recipients.

  • SOURCE CODE:

    import java.awt.*;import java.awt.event.*;import java.net.*;import java.io.*;

    public class MessageWindow extends Frame implements ActionListener,Runnable{public MessageWindow(){try{socket=new DatagramSocket();Integer port=new Integer(socket.getLocalPort());setTitle("Messenger(local port="+port.intValue()+")");}catch(Exception err){}addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}

  • });

    setSize(600,300);setBackground(Color.lightGray);setLayout(new BorderLayout());Panel p=new Panel(new FlowLayout(FlowLayout.CENTER));p.add(new Label("Host name:",Label.RIGHT));p.add(hostname);

    p.add(new Label("Port:",Label.RIGHT));p.add(portnum);Button b=new Button("Send!");b.addActionListener(this);p.add(b);add(p,"North");add(msg);Thread t=new Thread(this);t.start();}public void actionPerformed(ActionEvent event){if(event.getActionCommand().equals("Send!"))try{byte[] data=msg.getText().getBytes();

  • InetAddress addr=InetAddress.getByName(hostname.getText());Integer port=new Integer(portnum.getText());DatagramPacket pckt=new DatagramPacket(data,data.length,addr,port.intValue());socket.send(pckt);}catch(Exception err){}

    }public void run(){try{while(true){byte[] data=new byte[2048];DatagramPacket pckt=new DatagramPacket(data,data.length);socket.receive(pckt);String mdata = new String(pckt.getData());msg.setText(mdata);Message m=new Message(socket,pckt);m.show();}}catch(Exception err){}

  • }public static void main(String args[]){MessageWindow mw=new MessageWindow();mw.show();}private DatagramSocket socket;private TextArea msg=new TextArea();private TextField hostname=new TextField(10);private TextField portnum=new TextField(4);}

    class Message extends Frame implements ActionListener{public Message(DatagramSocket sock,DatagramPacket pckt){socket=sock;packet=pckt;try{String hostname=pckt.getAddress().getHostName();String addr=pckt.getAddress().getHostAddress();Integer port=new Integer(pckt.getPort());setTitle("Message from "+hostname+"("+addr+":"+port.intValue()+")");

  • }catch(Exception err){}

    addWindowListener(new WindowAdapter(){public void WindowClosing(WindowEvent e){System.exit(0);}});

    setSize(250,200);setBackground(new Color(225,225,225));setLayout(new BorderLayout());add(new Label("Edit message and press 'reply!'"),"North");String data=new String(pckt.getData());msg.setText(data);add(msg,"Center");Panel p=new Panel(new FlowLayout(FlowLayout.CENTER));Button b=new Button("Reply!");b.addActionListener(this);p.add(b);b=new Button("close");b.addActionListener(this);

  • p.add(b);add(p,"South");}

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

  • Ex. No. 15.Date:

    Implementation of Online test for a Single ClientAim

    To implement the online test for a single client using java programTheoryFileReader

    public class FileReaderextends InputStreamReader

    Convenience class for reading character files. The constructors of this class assume that thedefault character encoding and the default byte-buffer size are appropriate. To specify thesevalues yourself, construct an InputStreamReader on a FileInputStream.FileReader is meant for reading streams of characters. For reading streams of raw bytes, considerusing a FileInputStream.

  • SOURCE CODE FOR CLIENT:

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

    class OnlineTestClient{public static void main(String args[])throws IOException{InetAddress a=InetAddress.getLocalHost();Socket soc=new Socket(a,6789);String p;try{BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()));PrintWriter out=new PrintWriter(new OutputStreamWriter(soc.getOutputStream()),true);DataInputStream d=new DataInputStream(System.in);System.out.println(in.readLine());while(!(p=in.readLine()).equalsIgnoreCase("test session over")){System.out.println(p);out.println(d.readLine());}System.out.println(in.readLine());

  • }finally{soc.close();}}}

    SOURCE CODE FOR SERVER:

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

    class OnlineTestServer{public static void main(String args[])throws IOException{ServerSocket s=new ServerSocket(6789);Socket soc=s.accept();int nullSpaceRead;try

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

  • }}}

    CONTENTS TO BE ON E:\question.txt:Note: The numbering and space left should be as below without any changes.

    1) Translator for low level programming language were termed asa Assembler2) Shell is the exclusive feature ofb Unix3) The statement which is used to terminate the control from the loop isc Break4) Which feature in OOP allows reusing code?d Inheritance5) Set of values of the same type, which have a single name followed by an index is callede Array6) If a shift register can be operated in all possible ways then it is called as ______f Universal7) To hide a data member from the program, you must declare the data member in the _____section of the class.g Private

  • 8) The number of structures than can be declared in a single statement ish Unlimited9) Which technology is used in optical disks?i Laser10) What is IDE?j Integrated Development Environmenttest session over

    SAMPLE INPUT/OUTPUT:

    E:\EX15>javac OnlineTestServer.java

    E:\EX15>java OnlineTestServer

    E:\EX5>javac OnlineTestClient.java

    E:\EX5>java OnlineTestClient

  • Here is your Question1) Translator for low level programming language were termed asassembler2) Shell is the exclusive feature ofnix3) The statement which is used to terminate the control from the loop isbreak4) Which feature in OOP allows reusing code?inheritance5) Set of values of the same type, which have a single name followed by an index is calledarray6) If a shift register can be operated in all possible ways then it is called as ______cache7) To hide a data member from the program, you must declare the data member in the_____ section of the class.private8) The number of structures than can be declared in a single statement isunlimited9) Which technology is used in optical disks?mechanical10) What is IDE?integrated development environment

    You have scored 70 points


Recommended