Sie sind auf Seite 1von 39

CS9216 Networking Lab

Exercise Manual
(Anna University - Chennai) (Regulation 2009)

Compiled by,

MOHAN KUMAR R
1st Year ME CSE PABCET Trichy

mohan2912@gmail.com

Exercise No

: 01 a

Exercise Name: Socket Programming

AIM: ALGORITHM:

Implementation of TCP SERVER CLIENT Socket


To write a socket program to transfer data between server and client using TCP sockets.

SERVER: 1) Initialize the socket address structure with IP address family and port number. 2) Create a TCP Server Socket and a socket object. 3) Convert the server socket to listen the client request. 4) Accept the request which is sent by the TCP Client. 5) Receive data from the client by using RECEIVE() function & display it on IO console unit. 6) Send acknowledgment data to the client by using PRINTLN() function. CLIENT: 1) Initialize the socket address structure with IP address family and port number. 2) Create a TCP socket object and request the SERVER for connection. 3) Once the Connection request is accepted and connection established, send a HELLO message to the server by using PRINTLN() function. 4) RECEIVE() method is used to get response from the server. 5) Display the ACK message on IO Console unit. 6) Close the Socket connection and terminate the process. CODING: SERVER: import java.net.*; import java.io.*; public class TCP_Server { public static void main( String args[]) { ServerSocket sersock =null; Socket sock= null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; String Recv_msg="",Send_msg="Hello from server...\n"; try { sersock = new ServerSocket(1025);
mohan2912@gmail.com

System.out.println("Server Started :"+sersock); sock= sersock.accept(); System.out.println("\nClient Connected :"+ sock); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Dataout_soc=new PrintStream(sock.getOutputStream()); Recv_msg=Datain_soc.readLine(); System.out.println(Recv_msg); Dataout_soc.println(Send_msg); Dataout_soc.close(); sock.close(); } catch(Exception se){ System.out.println("Server Socket problem "+se.getMessage()); } }// main } // Server class CLIENT: import java.io.*; import java.net.*; class TCP_Client { public static void main(String args[]) { Socket sock=null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; String Recv_msg="",Send_msg="Hi From Client..."; System.out.println(" Trying to connect"); try { InetAddress ip =InetAddress.getLocalHost(); sock= new Socket(ip,1025); Dataout_soc= new PrintStream(sock.getOutputStream()); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Dataout_soc.println(Send_msg); Recv_msg=Datain_soc.readLine(); System.out.println(Recv_msg); Dataout_soc.close(); sock.close(); } catch(Exception e) { System.out.println("Exception " + e); } } // main } // Class Client
mohan2912@gmail.com

OUTPUT:

RESULT: Thus the TCP Server - Client Socket program has been done successfully and the output was verified.

mohan2912@gmail.com

Exercise No

: 01 b

Exercise Name: Socket Programming

IMPLEMENTATION OF UDP SOCKET


AIM: To write a java program to create a UDP Socket for transferring data over a network.

ALGORITHM: USER1: 1) Initialize the UDP Datagram Socket and Server IP Address details. 2) Declare DataInputStream & PrintStream objects for data reception and transmission. 3) Declare a buffer to store data with the size of Datagram Packet. 4) Receive data from the user in IO Console unit and store it in the buffer until either buffer become full or a NEWLINE character is encountered. 5) Send the content in the buffer and clear the buffer for next datagram packet. 6) Repeat the steps 4 & 5 until encountering the keystroke CTRL + C. 7) Close the connection and terminate the process. USER2: 1) Initialize the UDP Datagram Socket and Server IP Address details. 2) Declare DataInputStream & PrintStream objects for data reception and transmission. 3) Receive the datagram packet from the user1 and store it in a buffer. 4) Display the received content on IO Console unit. 5) Continue the steps 3 & 4 until encountering the CTRL + C Keystroke. 6) Close the connection and terminate the process. CODING: import java.net.*; class UDP_Program { public static int server_port=998; public static int client_port=999; public static byte buffer[]=new byte[1024]; public static DatagramSocket UDP_Soc; public static void Server() throws Exception { int pos=0; String str_temp=""; System.out.println("The UDP Server process has been initiated...\n"); System.out.println("Type the text content and \nPress ENTER key to send to the client : ");
mohan2912@gmail.com

do { int ch=System.in.read(); if(ch!='\n') { buffer[pos++]=(byte)ch; str_temp+=(char)ch; } else { UDP_Soc.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),client_port)); pos=0; str_temp=""; } }while(!str_temp.equalsIgnoreCase("quit")); } public static void Client() throws Exception { System.out.println("The UDP Client process has been initiated...\n"); DatagramPacket UDP_Pac=new DatagramPacket(buffer,buffer.length); System.out.println("Data Received from the server is,..\t"); do{ UDP_Soc.receive(UDP_Pac); System.out.println(new String(UDP_Pac.getData(),0,UDP_Pac.getLength())); }while(true); } public static void main(String args[]) throws Exception { if(args.length==0) { System.out.println("Please specify Server / Client to start corresponding instance..."); System.exit(0); } else if(args[0].equalsIgnoreCase("server")) { UDP_Soc=new DatagramSocket(server_port); Server(); } else if(args[0].equalsIgnoreCase("client")) { UDP_Soc=new DatagramSocket(client_port); Client(); } else { System.out.println("Invalid Command line argument..."); System.exit(0); } }

mohan2912@gmail.com

OUTPUT:

RESULT: Thus the implementation of UDP socket program has been done and the output was verified.

mohan2912@gmail.com

Exercise No

: 01 c

Exercise Name: Socket Programming

APPLICATION USING SOCKETS IMPLEMENTATION OF FTP


AIM: To write a java program to implement File Transfer Protocol (FTP) using TCP/IP Sockets.

ALGORITHM: SERVER: 1) Initialize the socket address structure with IP address family and port number. 2) Create a TCP Server Socket and a socket object. 3) Convert the server socket to listening socket and wait for the client request. 4) Accept the client connection and get the filename. 5) Open the specified file in read mode. 6) Read all contents in that file and store it in a buffer. 7) Send the buffered content to the client. 8) Close the socket connection. CLIENT: 1) Create a socket connection with the given port address. 2) Send a request to the server for connection. 3) Get a filename from the user in IO Console unit and send it to the server. 4) Receive data which is sent by the server and store it in a buffer. 5) Get a destination filename from the user. 6) Create a filename with the given filename in WRITE mode. 7) Write all received data in the destination filename. 8) Close the FileOutputStream object and Socket Connection. CODING: SERVER: import java.io.*; import java.net.*; class ftpserver { public static void main(String args[])throws IOException { char ch[] = new char[35]; String str; int i=0,j; ServerSocket ss = new ServerSocket(5600);
mohan2912@gmail.com

Socket s = ss.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); String fname = in.readLine(); FileInputStream fin = new FileInputStream(fname); while(true) { for(i=0;i<30;i++) { j=fin.read(); ch[i]=(char)j; if(j==-1) break; } str = new String(ch,0,i); out.println(str); if(i!=30) break; } out.println("EOF"); in.close(); out.close(); s.close(); ss.close(); } } CLIENT: import java.io.*; import java.net.*; class ftpclient { public static void main(String args[])throws Exception { BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the hostname to connect:"); Socket s = new Socket(InetAddress.getByName(in1.readLine()),5600); BufferedReader in2 = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(s.getOutputStream(),true); System.out.println("Enter the source filename:"); out.println(in1.readLine()); System.out.println("Enter the destination filename:"); FileOutputStream fout = new FileOutputStream(in1.readLine()); String data; int i=0; while(true) { data = in2.readLine(); if(data.equals("EOF")) break; char ch[] = new char[35]; data.getChars(0,data.length(),ch,0); for(i=0;i<data.length();i++) fout.write((int)ch[i]); } in1.close(); } }
mohan2912@gmail.com

in2.close();

out.close();

s.close();

fout.close();

CONTENT IN THE INPUT FILE:

(ex.txt)

OUTPUT:

RESULT: Thus the File Transfer Protocol program has been done successfully and the output was verified.

mohan2912@gmail.com

Exercise No

: 02

Exercise Name: IMPLEMENTATION OF SLIDING WINDOW PROTOCOL AIM:

To write a socket program in java to implement the sliding window technique.

ALGORITHM: SERVER: 1) Initialize the required header files and variables with default values. 2) Get the size of the sliding window. If it is not specified, then set the window size to default value of 3. 3) Create a server socket and wait for the client request. 4) Accept the client request and establish a connection with the client with sending the sliding window size. 5) Receive data frame from the client and display the received content. 6) Increment the frame counter value by 1. 7) Check the frame counter value. If the frame-counter value is same as sliding window size means, send an ACK message to the client and re-initialize the frame counter value to 0. Otherwise, Proceed to next step. 8) Repeat the steps from 5 to 7. CLIENT: 1) Initialize the socket address with client socket address family and port number details. 2) Send a request to the server and once the connection is established, get the size of the sliding window. 3) Get the input from the user on IO Console unit and send it to the server. 4) Increment the packet-send counter value by 1. 5) Repeat the step 3 & 4 until packet-send counter values becomes equal to sliding window size. Then proceed to step 6. 6) Wait for an ACK message from the server for already sent packets. 7) Display the received ACK message on IO Console unit and re-initialize the packet-send counter value to 1. 8) Repeat the steps from 3 & continue the process until encountering the keystroke CTRL + C.
mohan2912@gmail.com

CODING: SERVER: import java.io.*; import java.net.*; public class SlidingWnd_Server { public static void main( String args[]) { ServerSocket sersock =null; Socket sock= null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; int Wnd_size,frame_count=0,Ack_No=1; String Send_msg,Recv_msg; if(args.length>0) { Wnd_size=Integer.parseInt(args[0]); if(Wnd_size<=0) { System.out.println("\nSliding window size is set to default value\nWindow Size : 3\n"); Wnd_size=3; } } else { System.out.println("\nSliding window size is set to default value\nWindow Size : 3\n"); Wnd_size=3; } try { sersock = new ServerSocket(1025); System.out.println("Server Started :\n"+sersock); sock= sersock.accept(); System.out.println("\nClient Connected :\n"+ sock+"\n"); System.out.println("Message received:\n================="); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Dataout_soc=new PrintStream(sock.getOutputStream()); Dataout_soc.println(Wnd_size); while(true) { if(frame_count!=Wnd_size)
mohan2912@gmail.com

{ Recv_msg=Datain_soc.readLine(); System.out.println(Recv_msg); frame_count++;

} else { Send_msg=Ack_No+""; Ack_No++; System.out.println("Acknowledgement has been sent for last "+Wnd_size+" packets...\n"); Dataout_soc.println(Send_msg); frame_count=0; } } } catch(Exception se) { System.out.println("Server Socket problem "+se.getMessage()); } } // main } // Server class CLIENT: import java.io.*; import java.net.*; class SlidingWnd_Client { public static void main(String args[]) { Socket sock=null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; int Wnd_size,frame_count=0; String Send_msg,Recv_msg; try { InetAddress ip =InetAddress.getLocalHost(); sock= new Socket(ip,1025); Dataout_soc= new PrintStream(sock.getOutputStream()); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Wnd_size=Integer.parseInt(Datain_soc.readLine()); System.out.println("\nSliding Window Size : "+Wnd_size); System.out.println("Type the message her and press enter to send...\n"); while(true) {
mohan2912@gmail.com

if(frame_count!=Wnd_size) { Send_msg=Datain_con.readLine().toString(); Dataout_soc.println(Send_msg); frame_count++; } else { Recv_msg=Datain_soc.readLine(); System.out.println("Transmission Success Acknowledgement "+Recv_msg+")\n"); frame_count=0; } } } catch(Exception e) { System.out.println("Exception " + e.getMessage()); } } // main } // Client class

(Ack No :

mohan2912@gmail.com

OUTPUT:

RESULT: Thus the Sliding window protocol implementation program has been done successfully.

mohan2912@gmail.com

Exercise No

: 03 DIJKSTRAS ALGORITHM

Exercise Name: IMPLEMENTATION OF ROUTING PROTOCOL

AIM: To write a java program to implement the dijkstra routing algorithm. ALGORITHM: 1) Declare the required packages and variables. 2) Create graph vertices and initialize with default weight value & MinDistance. 3) Specify the graph adjacent nodes and its path cost for each vertex. 4) Assign a node as Source node. 5) Compute the shortest path from the assigned source node and its minimal path cost. 6) Display the list of nodes and corresponding minimal path cost. And also display the route details from the source node to the corresponding node. 7) Flush the object and terminate the process. CODING: import java.util.PriorityQueue; import java.util.List; import java.util.ArrayList; import java.util.Collections; class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = 1000; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other) { return Double.compare(minDistance, other.minDistance); }

mohan2912@gmail.com

class Edge { public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; } } public class Dijkstra { public static void computePaths(Vertex source) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU ; v.previous = u; vertexQueue.add(v); } } } } public static List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex.previous) path.add(vertex); Collections.reverse(path); return path; }

mohan2912@gmail.com

public static void main(String[] args) { Vertex v1 = new Vertex("a"); Vertex v2 = new Vertex("b"); Vertex v3 = new Vertex("c"); Vertex v4 = new Vertex("d"); Vertex v5 = new Vertex("f"); v1.adjacencies = new Edge[]{ new Edge(v2, 5), new Edge(v3, 10), new Edge(v4, 8) }; v2.adjacencies = new Edge[]{ new Edge(v1, 5), new Edge(v3, 3), new Edge(v5, 7) }; v3.adjacencies = new Edge[]{ new Edge(v1, 10), new Edge(v2, 3) }; v4.adjacencies = new Edge[]{ new Edge(v1, 8), new Edge(v5, 2) }; v5.adjacencies = new Edge[]{ new Edge(v2, 7), new Edge(v4, 2) }; Vertex[] vertices = { v1, v2, v3, v4, v5 }; computePaths(v1); for (Vertex v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } OUTPUT:

RESULT: Thus the implementation of dijkstra algorithm has been done and the output was verified.

mohan2912@gmail.com

Exercise No

: 04 a

Exercise Name: IMPLEMENTATION OF DNS SERVICE AIM: To write a program to implement Domain Name Server (DNS) Service using TCP/IP Socket. ALGORITHM: SERVER: 1) Declare the required variables and define the required methods. 2) Initialize IP Address buffer and corresponding Host Name buffer. 3) Create a server socket by specifying the Port number and server IP address details. 4) Wait for the client request and establish the connection once the request is received. 5) Get IP-REQUEST message from the client. 6) Compare the received IP address with the IP-Address list buffer. If it is found, and then get the IP-INDEX value. Otherwise, send -1 to the client and go to step 8. 7) Get the corresponding host name for the assigned IP-INDEX value and transmit the HOST NAME to the client. 8) Close the client socket connection and terminate the process. CLIENT: 1) Initialize the client socket and send a request to the server. 2) Get the IP Address from the user in IO Console unit to find the corresponding HOST NAME. 3) Send the IP-REQUEST message to the server. 4) Receive the server response and check the received content. If it is -1, display an error message as HOST NOT FOUND. Otherwise, Display the received message i.e. HOST NAME for the given IP Address. 5) Close the socket connection and terminate the process. CODING: SERVER: import java.net.*; import java.io.*; public class DNS_Server { public static void main( String args[]) { ServerSocket sersock =null;
mohan2912@gmail.com

String IP_Address[]={"192.168.100.1","192.168.200.1","192.168.300.1","192.168.400.1","192.16 8.500.1"}; String Host_Name[]={"Network Lab","Communication Lab","Operating Systems Lab","Software Engineering Lab","Multimedia Lab"}; String Send_msg,Recv_msg=""; try { sersock = new ServerSocket(1025); System.out.println("Server Started :\n"+sersock); sock= sersock.accept(); System.out.println("\nClient Connected :\n"+ sock); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Dataout_soc=new PrintStream(sock.getOutputStream()); Recv_msg=Datain_soc.readLine(); System.out.println("Request received : "+Recv_msg); int Host_Found=-1; for(int i=0;i<5;i++) { if(IP_Address[i].equals(Recv_msg)) Host_Found=i; } if(Host_Found!=-1) Dataout_soc.println(Host_Name[Host_Found]); else Dataout_soc.println(Host_Found); Dataout_soc.close(); sock.close(); } catch(Exception se) { System.out.println("Server Socket problem "+se.getMessage()); } } // main } // Server class

Socket sock= null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null;

mohan2912@gmail.com

CLIENT: import java.io.*; import java.net.*; class Client { public static void main(String args[]) { Socket sock=null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; String Send_msg,Recv_msg=""; try { InetAddress ip =InetAddress.getLocalHost(); sock= new Socket(ip,1025); Dataout_soc= new PrintStream(sock.getOutputStream()); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); System.out.println("\n\t\t * * * Implementation of DNS Service * * *"); System.out.print("Enter the IP address : "); Send_msg=Datain_con.readLine(); Dataout_soc.println(Send_msg); Recv_msg=Datain_soc.readLine(); if(!Recv_msg.equals("-1")) { System.out.println("Host name of the given IP : "); System.out.println(Recv_msg); } else System.out.println("System is not found with the given IP..."); Dataout_soc.close(); sock.close();

} catch(Exception se) { System.out.println("Exception " +se.getMessage()); } } // main } // Client class

mohan2912@gmail.com

OUTPUT:

RESULT: Thus the implementation of DNS service has been done in java and the output was verified.

mohan2912@gmail.com

Exercise No

: 04 b

Exercise Name: IMPLEMENTATION OF HTTP SERVER AIM:

To write a java program to implement the HTTP server with multithreading concept.

ALGORITHM: 1) Declare the required header file and initialize the variables with default values. 2) Create a TCP server socket with the port number 100. 3) Wait for the client request and accept the request. 4) Create a separate thread for each client request. For each thread, continue the following steps, 5) Initialize the request parameters and store them in variables. 6) Get the request file name and compare the request type whether it is GET or POST request. 7) Initialize the StringTokenizer object and parse the input file name. 8) Read the content in the requested file name. 9) Send the buffer content to the client and repeat the steps 8 & 9 until reading the EOF. 10) Display the request-response status. 11) Stop the thread and close the corresponding client connection. CODING: import java.io.*; import java.net.*; import java.util.*; import java.lang.*; public class HttpServer { public static void main(String [] args) { int i=1; System.out.println(" * * * HTTP SERVER * * *"); System.out.println("Server Started..."); System.out.println("Waiting for connections..."); try { ServerSocket s = new ServerSocket(100); for(;;) { Socket incoming = s.accept();
mohan2912@gmail.com

System.out.println("New Client Connected with id " + i+" from "+incoming.getInetAddress().getHostName()+"\n"); System.out.println("REQUEST HEADER"); Thread t = new ThreadedServer(incoming,i); i++; t.start(); } } catch(Exception e) {} } } class ThreadedServer extends Thread { final static String CRLF = ""; Socket incoming; int counter; public ThreadedServer(Socket i,int c) { incoming=i; counter=c; } public void run() { try { String statusline=null,contenttypeline=null,contentlength=null; String headerline,entitybody=null,venderline="Server: EXECUTER 1.1"; BufferedReader in =new BufferedReader(new InputStreamReader (incoming.getInputStream())); PrintWriter out = new PrintWriter(incoming.getOutputStream(), true); OutputStream output=incoming.getOutputStream(); headerline=in.readLine(); System.out.println(headerline); StringTokenizer s = new StringTokenizer(headerline); String meth = s.nextToken(); if(meth.equals("GET")||meth.equals("POST")) { int dot1,dot2,fslash; String fname,ext,FileName; String url = s.nextToken(); dot1=url.indexOf('.'); dot2=url.lastIndexOf('.'); fslash=url.lastIndexOf('/'); fname=url.substring(dot1+1,dot2); ext=url.substring(dot2,fslash); FileName=fname+ext; if(ext.equals(".html")||ext.equals(".htm")) {
mohan2912@gmail.com

FileInputStream fis=null; boolean filexists=true; try { fis=new FileInputStream(FileName); } catch(FileNotFoundException e) { System.out.println("Exception: "+e.getMessage()); filexists=false; } if(filexists) { statusline=" HTTP/1.1 200 Ok"+CRLF; contenttypeline="Content-Type: text/html "+CRLF; contentlength="Content-Length:"+(new Integer(fis.available())).toString() + CRLF; } else { statusline = "HTTP/1.0 404 Not Found" + CRLF ; contenttypeline = "Content-Type: text/html"+CRLF ; entitybody = "<HTML>" + "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" + "<BODY><H1>404 File Not Found</H1></BODY></HTML>" ; } output.write(statusline.getBytes()); output.write(venderline.getBytes()); output.write(contentlength.getBytes()); output.write(contenttypeline.getBytes()); output.write(CRLF.getBytes()); if (filexists) { sendBytes(fis, output) ; fis.close(); } else { output.write(entitybody.getBytes()); } } else { statusline = "HTTP/1.0 400 Not Found" + CRLF ; contenttypeline = "Content-Type: text/html"+CRLF ; entitybody = "<HTML>" + "<HEAD><TITLE>400</TITLE></HEAD>" + "<BODY><H1>400 A malformed HTTP request is received</H1></BODY></HTML>"; } } else { statusline = "HTTP/1.0 400 Not Found" + CRLF ; contenttypeline = "Content-Type: text/html"+CRLF ;
mohan2912@gmail.com

entitybody = "<HTML>" + "<HEAD><TITLE>400</TITLE></HEAD>" +"<BODY><H1>400 A malformed HTTP request is received</H1></BODY></HTML>"; } boolean done=false; while(!done) { headerline=in.readLine(); if(headerline == null) done = true; else System.out.println(headerline); } incoming.close(); in.close(); out.close(); } catch(Exception e) {} } private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception { byte[] buffer = new byte[1024] ; int bytes = 0 ; while ((bytes = fis.read(buffer)) != -1 ) { os.write(buffer, 0, bytes); } } }

mohan2912@gmail.com

HOW TO RUN THE HTTP SERVER: To execute the program using LOCALHOST, follow the steps: 1. Install HttpServer.java on one system 2. Configure your browser using following steps: a. Go to Tools. b. Go to Internet Options. c. Go to Connections. d. Go to LAN Setting. e. Select Use a proxy server for your LAN. f. Make Address: http://localhost & Port: 100 3. Run HttpServer.java 4. Run browser 5. Put filename.html into the bin of jdk 6. Place a request using following format:http://localhost.filename.html/ Where filename.html is the name of the file you want to request. OUTPUT:

RESULT: Thus the simulation of HTTP Server service has been done and the output was verified.

mohan2912@gmail.com

Exercise No

: 04 c

Exercise Name: IMPLEMENTATION OF E-MAIL CLIENT APPLICATION AIM:

To write a java program to implement an e-mail client application using SWING components. ALGORITHM: 1) Declare the required java packages and javax swing packages. 2) Declare and initialize the mail account details. 3) Initialize the mail server details such as host name, port number, SSL_FACTORY, session details and swing properties. 4) Declare and initialize the mail account details such as subject, messages, TO address list and File attachment details. 5) Initialize the internet SSL provider object and its methods. 6) Establish a connection with the mail server. 7) Create a message packet using MimeMessage object. 8) Send the message to designed recipients. 9) Close the server connection and terminate the process. CODING: import java.io.File; import java.security.Security; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class Email_Test { private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final String SMTP_PORT = "465";
mohan2912@gmail.com

private static final String emailMsgTxt = "Test Message Contents"; private static final String emailSubjectTxt = "A test from gmail"; private static final String emailFromAddress = "xxx@gmail.com"; private static final String SSL_FACTORY ="javax.net.ssl.SSLSocketFactory"; private static final String[] sendTo = {"xxx@gmail.com","xxx@yahoo.com"}; private static final String fileAttachment="D:\\hai.txt"; public static void main(String args[]) throws Exception { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); new Email_Test().sendSSLMessage(sendTo, emailSubjectTxt, emailFromAddress); System.out.println("Sucessfully Sent mail to All Users"); }

emailMsgTxt,

public void sendSSLMessage(String recipients[], String subject, String message, String from) throws MessagingException { boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("xxx@gmail.com", "give password of gmail"); } } ); MimeMessage message1 =new MimeMessage(session); message1.setFrom(new InternetAddress(from)); message1.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients[0])); message1.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients[1])); message1.setSubject("Hello JavaMail Attachment"); // create the message part MimeBodyPart messageBodyPart =new MimeBodyPart(); //fill message messageBodyPart.setText("Hi");
mohan2912@gmail.com

Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source =new FileDataSource(fileAttachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileAttachment); multipart.addBodyPart(messageBodyPart); // Put parts in message message1.setContent(multipart); // Send the message Transport.send( message1 ); } }

RESULT: Thus the e-mail client application program using swing component has been done.

mohan2912@gmail.com

Exercise No

: 04 d

Exercise Name: MULTI-USER CHAT APPLICATION AIM:

To write a program to develop multi user chat application using sockets.

ALGORITHM: SERVER: 1) Initialize the socket address structure with IP address and port details. 2) Create a server socket and listen to client request. 3) Accept the client request and create a separate thread instance for every client request. 4) In each thread, get the screen name for the client and assign a unique id. 5) Receive message from the connected clients and broadcast it to all available clients. 6) If a client connection is terminated, remove that particular client IP details from the client list. 7) Finally close all client connections and close the server socket. CLIENT: 1) Declare the required header file and variables. 2) Create a socket and send a request to the server. 3) Once the connection is established, get the user screen name from the user and assign to the particular chat client instance. 4) Get the message from the user and send it to the server using PRINTLN () function. 5) Receive messages from server using RECEIVE () method and display it. 6) Finally close the socket connection and terminate the process. CODING: SERVER: import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static HashSet<String> names = new HashSet<String>(); private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>(); public static void main(String[] args) throws Exception {
mohan2912@gmail.com

ServerSocket listener = new ServerSocket(8167); System.out.println("The chat server is running."); try { while (true) { new Handler(listener.accept()).start(); } } finally { listener.close(); } } private static class Handler extends Thread { private String name; private Socket socket; private BufferedReader in; private PrintWriter out; public Handler(Socket socket) { this.socket = socket; } public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); while (true) { out.println("SUBMITNAME"); name = in.readLine(); if (name == null) return; synchronized (names) { if (!names.contains(name)) { names.add(name); break; } } } out.println("NAMEACCEPTED"); writers.add(out); while (true) { String input = in.readLine(); if (input == null) return; for (PrintWriter writer : writers) writer.println("MESSAGE " + name + ": " + input);
mohan2912@gmail.com

} } catch (IOException e) { System.out.println(e); } finally { if (name != null) names.remove(name); if (out != null) writers.remove(out); try { socket.close(); } catch (IOException e) { } } } } }

CLIENT: import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.*; public class ChatClient { BufferedReader in; PrintWriter out; JFrame frame = new JFrame("Chatter"); JTextField textField = new JTextField(40); JTextArea messageArea = new JTextArea(8, 40); public ChatClient() { textField.setEditable(false); messageArea.setEditable(false); frame.getContentPane().add(textField, "North"); frame.getContentPane().add(new JScrollPane(messageArea), "Center"); frame.pack(); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { out.println(textField.getText()); textField.setText(""); } }); } private String getServerAddress()
mohan2912@gmail.com

{ return JOptionPane.showInputDialog( frame, "Enter IP Address of the Server:", "Welcome to the Chatter", JOptionPane.QUESTION_MESSAGE);

private String getName() { return JOptionPane.showInputDialog( frame, "Choose a screen name:", "Screen name selection", JOptionPane.PLAIN_MESSAGE); } private void run() throws IOException { String line,serverAddress = getServerAddress(); Socket socket = new Socket(serverAddress, 8167); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); while (true) { line = in.readLine(); if (line.startsWith("SUBMITNAME")) { out.println(getName()); } else if (line.startsWith("NAMEACCEPTED")) { textField.setEditable(true); } else if (line.startsWith("MESSAGE")) { messageArea.append(line.substring(8) + "\n"); } } } public static void main(String[] args) throws Exception { ChatClient client = new ChatClient(); client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.frame.setVisible(true); client.run(); } }
mohan2912@gmail.com

OUTPUT: Note: 1) 2) 3) 4) 5) 6) Compile the server program and run the server program. Leave the server instance console window as it is. Compile and run more than one client programs. Give the server detail as localhost. Give different & unique screen name for every client window. Start chatting.

RESULT: Thus the multi user chat application program has been done and the output was verified.

mohan2912@gmail.com

Exercise No

: 05

Exercise Name: IMPLEMENTATION OF NETWORK MANAGEMENT PROTOCOL

IMPLEMENTATION OF RARP
AIM: To write a program to implement Reverse Address Resolution Protocol. ALGORITHM: SERVER: 1) 2) 3) 4) 5) 6) Declare the required variables and define the required methods. Initialize IP Address buffer and corresponding MAC Address buffer. Create a server socket by specifying the Port number and server IP address details. Wait for the client request and establish the connection once the request is received. Get IP-REQUEST message from the client. Compare the received MAC address with the MAC-Address list buffer. If it is found, and then get the MAC-INDEX value. Otherwise, send -1 to the client and go to step 8. 7) 8) CLIENT: 1) 2) 3) 4) Initialize the client socket and send a request to the server. Get the MAC Address from the user in IO Console unit to find the corresponding IP Address. Send the IP-REQUEST message to the server. Receive the server response and check the received content. If it is -1, display an error message as HOST NOT FOUND. Otherwise, Display the received message i.e. IP Address for the given MAC Address. 5) Close the socket connection and terminate the process. Get the corresponding IP Address for the assigned MAC-INDEX value and transmit the IP Address to the client. Close the client socket connection and terminate the process.

mohan2912@gmail.com

CODING: SERVER: import java.net.*; import java.io.*; public class RARP_Server { public static void main(String args[]) { ServerSocket sersock =null; Socket sock= null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; String IP_Address[]= {"192.168.100.1","192.168.200.1","192.168.300.1","192.168.400.1","192.168.500.1"}; String MAC_ADDRESS[]= {"57N-H348-B2AQ-OIJY-6","93X-H64L-42AM-WHKY-4","I0V-JK482TAB-BEJY-8","89X-IOZ8-6ZLB-DHJY-3","XJH-4UI8-3IAP-BPYS-7"}; String Send_msg,Recv_msg=""; try { sersock = new ServerSocket(1025); System.out.println("Server Started :\n"+sersock); sock= sersock.accept(); System.out.println("\nClient Connected :\n"+ sock); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); Dataout_soc=new PrintStream(sock.getOutputStream()); Recv_msg=Datain_soc.readLine(); System.out.println("Request received : "+Recv_msg); int Host_Found=-1; for(int i=0;i<5;i++) { if(MAC_ADDRESS[i].equals(Recv_msg)) Host_Found=i; } if(Host_Found!=-1) Dataout_soc.println(IP_Address[Host_Found]); else Dataout_soc.println(Host_Found); Dataout_soc.close(); sock.close(); } catch(Exception se) {} } // main } // Server class

mohan2912@gmail.com

CLIENT: import java.io.*; import java.net.*; class Client { public static void main(String args[]) { Socket sock=null; DataInputStream Datain_soc=null; DataInputStream Datain_con=null; PrintStream Dataout_soc=null; String Send_msg,Recv_msg=""; try { InetAddress ip =InetAddress.getLocalHost(); sock= new Socket(ip,1025); Dataout_soc= new PrintStream(sock.getOutputStream()); Datain_soc = new DataInputStream(sock.getInputStream()); Datain_con=new DataInputStream(System.in); System.out.println("\n\t\t * * * Implementation of RARP * * *"); System.out.print("Enter the MAC Address : "); Send_msg=Datain_con.readLine(); Dataout_soc.println(Send_msg); Recv_msg=Datain_soc.readLine(); if(!Recv_msg.equals("-1")) { System.out.println("IP Address of the given MAC Address : "); System.out.println(Recv_msg); } else System.out.println("HOST NOT FOUND"); Dataout_soc.close(); sock.close();

} catch(Exception se) { System.out.println("Exception " +se.getMessage()); } } // main } // Client class

mohan2912@gmail.com

OUTPUT:

RESULT: Thus the implementation of RARP algorithm has been done and the output was verified.

mohan2912@gmail.com

Das könnte Ihnen auch gefallen