32
Question 1 a) Java is called as write once run anywhere because when one write Java code and compiles it or runs it; Java Virtual Machine (JVM) of that system creates a byte code which is dependent on the JVM not the machine where it is written or compiled. JVM generated byte code can run on any machine and on any operation system. Java provides three different kinds of portability, source code portability, CPU architecture portability and OS/GUI portability. Source Code Portability: Java program produces the same result regardless of operation system and machine architecture. C and C++ program also allows to the same but in most of the cases it is not the same. CPU architecture portability: Most of the languages produce the compiled or byte code file which runs on the same type of architecture say x86 architecture but JVM produced byte code file can run on any kind of family where JVM is installed. OS/GUI portability: Program written in C or C++ with graphics on windows, it is really difficult to port on the non-Windows platform, and even if the extra care of porting is taken care of it does not produces the same result as it should. Whereas java provides the packages and library which are same for each JVM so even if the GUI code is written on Windows platform it gives the same output on the non-windows platform without any extra care of porting. Write once run anywhere is not completely justifiable at some places like when running the byte code on different environment form where it generated it might not have some function like garbage collection and Just in Time compilers which allows the code to alter and make a fast execution. Mobile phones still does not have the functionality of write once run anywhere. Servers like web server and LDAP servers becomes difficult to run the same native or byte code. b) Inheritance is the process in which one can have all the attributes of the other object like for example manager can have all the attributes of employee it has to define only the unique feature of him. It can be used by using extends keyword or implement keyword. Benefits of Inheritance to software developer: 1. Code reuse: One can write the code which will be used many times only once in a base class and the classes which require the code can use it by using extend keyword.

Network Programming

  • Upload
    elkavio

  • View
    35

  • Download
    2

Embed Size (px)

DESCRIPTION

ILP report of Network Programming with coding result and instructions for run

Citation preview

Page 1: Network Programming

Question 1

a) Java is called as write once run anywhere because when one write Java code and compiles it or runs it; Java Virtual Machine (JVM) of that system creates a byte code which is dependent on the JVM not the machine where it is written or compiled. JVM generated byte code can run on any machine and on any operation system. Java provides three different kinds of portability, source code portability, CPU architecture portability and OS/GUI portability.

Source Code Portability: Java program produces the same result regardless of operation system and machine architecture. C and C++ program also allows to the same but in most of the cases it is not the same.

CPU architecture portability: Most of the languages produce the compiled or byte code file which runs on the same type of architecture say x86 architecture but JVM produced byte code file can run on any kind of family where JVM is installed.

OS/GUI portability: Program written in C or C++ with graphics on windows, it is really difficult to port on the non-Windows platform, and even if the extra care of porting is taken care of it does not produces the same result as it should. Whereas java provides the packages and library which are same for each JVM so even if the GUI code is written on Windows platform it gives the same output on the non-windows platform without any extra care of porting.

Write once run anywhere is not completely justifiable at some places like when running the byte code on different environment form where it generated it might not have some function like garbage collection and Just in Time compilers which allows the code to alter and make a fast execution. Mobile phones still does not have the functionality of write once run anywhere. Servers like web server and LDAP servers becomes difficult to run the same native or byte code.

b) Inheritance is the process in which one can have all the attributes of the other object like for example manager can have all the attributes of employee it has to define only the unique feature of him. It can be used by using extends keyword or implement keyword. Benefits of Inheritance to software developer: 1. Code reuse: One can write the code which will be used many times only once in a

base class and the classes which require the code can use it by using extend keyword.

Page 2: Network Programming

For example class B extends class A then all the code of class A is included in class B unless it is made private.

2. In java there can only be one base class or parent class to extend from but with the use of implements one class can have multiple signatures of as many classes requires.

3. With the use of final word with variable or methods it cannot changed by any derived class but can be called using the object. It removes the overhead of calling the method within the derived class and changed it and duplicating it.

4. Abstract class is also another feature of inheritance where a class is defined as abstract which may or may not have the abstract methods and it only can be sub- classed where methods just the have the definition but not the implementation. One can write the methods and its structures but it is left to implement later on when it is needed according to specific need.

c) Shallow copy is the copy where it copies only the main object, reference to that object is shared by both original object and cloned object. Whereas in deep copy it copies the main object as well as it references.

Fig 1 Shallow Copy

Main obj1

Contained obj1

Main obj2

Field 2 Field 1

Page 3: Network Programming

Fig 2 Deep Copy

d) Interface class in java is the normal class which has constants, method signatures but not body.

Abstract class in java is defined as abstract which may or may not have the abstract methods and it only can be sub- classed where methods just the have the definition but not the implementation.

Interface classes allows user to design it from the start where its primary purpose is different from the original one. All the methods in interface class should be public. Abstract class has the structures rather you can say is it defines the implementation and provides the method to build some more.

Question 2

a) Error exceptions are those which arise from outside of application and they cannot be predicted and difficult to handled and recover from it. Exceptions can be thrown for this kind but they are less helpful. For example illegal access error, out of memory error, thread death error.

Contained obj1

Main obj1

Field2

Contained obj2

Main obj2

Field 1

Page 4: Network Programming

Runtime Exception is those arise because of the mistake from programmer while building the application. For example arithmetic exception, array out of bound exception, null pointer exception. IO exception is the exceptions which arise during handling file system. It can be predicted and should be handled while building the application. For example file not found exception, End of file exception.

b) Checked exceptions are the exceptions which are checked during the compile time of piece of code. For example creating a new socket for connecting to server if it is not in the try catch block it will throw an exception. IO exception, class not found exception are some examples of checked exception. Unchecked exceptions are the exceptions are not checked during the compile time but they are checked at the run time like accessing array member out of bound. NullPointer Exception, ArrayOutofBound exception are some example of unchecked exception.

c) import java.io.*;

public class FileReader {

public static void main(String[] args) {

try {

File stockInputFile = new File("C://Sample/sample.txt");

File StockOutputFile = new File("C://Sample/sample1.txt");

FileInputStream fis = new FileInputStream(stockInputFile);

FileOutputStream fos = new FileOutputStream(StockOutputFile);

int count;

while ((count = fis.read()) != -1) {

fos.write(count);

}

fis.close();

fos.close();

} catch (FileNotFoundException e) {

Page 5: Network Programming

System.err.println("FileStreamsReadnWrite: " + e);

} catch (IOException e) {

System.err.println("FileStreamsReadnWrite: " + e);

}

}

}

d) Exception which is not handled at the time of writing the code and it is left to handle at the higher level is called propagating exception. Example is as below: Public void abc() throws ExceptionType1 { Try { // some code which throws exception

} catch (ExceptionType1 e) { Throw e;

} } Method abc lies in one class A and Class B will call method abc and that’s how exception is propagated.

Question 3

a) Public methods and variables are accessible to everyone Private methods and variables are only accessible within scope only. For example variable declare in the class is only accessible throughout that class only not outside the class. Protected methods and variables are accessible through out class, subclass and package. Default methods and variable are accessible through out class and package.

Modifier Class Package Subclass World Public Access Access access Access Protected Access Access Access Denied Default Access Access Denied Denied Private Access Denied Denied Denied

Page 6: Network Programming

b) Java program performs input/output by using streams. Stream is abstraction of either

taking some data or producing some data. Java I/O system links Stream to physical device. InputStream and OutputStream takes byte data. It belongs to byte streams. InputStream and OutputStream does not support Unicode characters. Reader and writer are character oriented streams. Reader and Writer belongs to Character Stream and it supports Unicode characters.

c) IO stream layering technique is achieved by java. In between stream are not the direct source of IO streams but they the wrappers around and already existing streams called as underlying streams. Layering technique tries to combine functionality of two different streams in order to achieve more convenient interfaces. The read and write methods either buffer the data or transform it before forwarding it to the underlying stream. Examples of intermediate streams are BufferedInputStream, BufferedOutputStream and so on. Import java.net.*; Import java.IO.*; Public class DoubleReader {

Public static void main(String [] args) { Try{ URL u = new URL(“FTP”, “www.poly.edu”, 21/RFC/rfcg5g.txt); URLConnection UC = u.openconnection(); UC.connect(); InputStream in = UC.getInputStream(); DataInputStream din = new DataInputStream (in); For (double C = din.readDouble(); c!= -1.0;C = din.readDouble()){ system.out.write(c); }

} catch(10 Exeption EOFException) { sys.out.print ("File has ended. unexpectedly"); } finally{ din.close(); }

}

Page 7: Network Programming

Question 4

a) Super() calls the constructor of square class as Square class which is square() because it is the base class for rectangle and it is same for super(w) which calls the square(int w) constructor of the Square class.

b) Significance of the final that appears in the header of the instance method printLn() defined in square is that this method cannot be overridden by its subclass.

c) Each and every variable defined in the class square are inherited by the Rectangle except the variable className type of String because it is declare as private. Private variables has the scope of that class only where as protected variables can be access by the subclass.

d) Each and every method defined in the class square is inherited by the Rectangle except printLn method because it is defined as final. Methods defined as final cannot be overridden so it is not inherited. Other methods are normal methods so subclass can access them.

e) i) Array type of Square can be safely used to store both Square and Rectangle objects because Rectangle is part of Square and it can store the object its subclasses. ii) When square[i].println() is called first time it will called the findArea() and findPerim() of Square class because first object of array belongs to Square type. Second time and third time that is square[1].println() and square[2].println() that time it call the methods of Rectangle class because even the object is stored in the array of Square but the actual object belongs to Rectangle class.

Questing 5

a) public class ExampleArray { public static void main(String[] args) { // TODO code application logic here //Creating array of String; String[] anarray; //Allocating Memory; anarray = new String[5]; //filling array; anarray[0] = "hello"; anarray[1] = "testing"; anarray[2] = "array"; anarray[3] = "filling"; anarray[4] = "&accessing"; //accessing array; for(int i = 0; i<5;i++){ System.out.println("Element at" + i +" " +anarray[i]);

Page 8: Network Programming

} } }

b) package examplearray; import java.util.ArrayList; import java.util.Collections; import java.util.List;

public static void main(String[] args) {

//Creating arraylist of String;

List mylist = new ArrayList();

String[] name = new String[]{"Hello", "Test", "Example"}; Collections.addAll(mylist,name); for(String s : name){ System.out.println(s); } } }

c) Size of an array cannot grow or shrink whereas arraylist can grows and shrink dynamically. Arraylist supports binary search. Arraylist can work with two different thread or instance as the same time. Arrays cannot.

d) Arraylist can only objects not the primitive data types. Double is primitive data type.

double a = 44.44;

Double floatObj = new Double(a);

list.add(44.44);

list.add(0,floatObj);

Page 9: Network Programming

double num = floatObj.doublea();

double num = list.get(index);

e) Sort and Search methods for arrays

Sort(array [] a);

Array can be of integer, character, float, double, float, byte, object and so on. It uses quick sort method for sorting.

Array uses binary search for searching method but arrays must be sorted before search function called.

Sort and Search methods for arraylist: If the data in the arraylist has natural sorting order then it can be done using Collections.sort(arraylist) method. If data not in natural sorting order then you have to built a comparator. Collections.sort(arraylist, comparator)

Question 6

Thread is a thread of execution in a program. Java allows application to running multiple threads. Threads has priority, the highest priority thread runs first and so on.

a) As class Even is public it can be called by any other classes and it is not thread-safe it might be possible that two classes are calling next method of class Even concurrently and it might result into not getting even number at the end. Let’s say class A call method next first at it is at step ++n mean time class B had also called the method and it is also running. As a result both classes calling same time one class might get the odd number.

b) public class Even

{

public int n = 0;

public int next()

{

++n;

++n;

Page 10: Network Programming

return n;

}

}

This could be one solution, other solution can be use thread for the next method so that it can execute it concurrently. One more solution can be providing locks on shared variables.

c) A new thread will start if it invoke thread.start() all other invocations remain in the main thread.

Public class testThread() implements Runnable{

Public void run(){

//sample code here

}

Public static void main(String[] args){

(new Thread(new testTread()).start();

}

}

Question 7

a) A socket is an end point communication link for two programs which are trying to run on the network. URL and URL connections provides high level of networking sometimes programs needs to connect using low-level networking for example telnet or writing a client server application.

“Sockets are available as long as the network process maintains an open link to the socket. A socket can be named in order to communicate with other sockets in a network. Communication is performed by the sockets in network when the server receives the connections and requests from them. Message can also be shared between a client and the server. Pairs of sockets can be created.”

b) Server: import java.io.*; import java.net.*; import java.util.*;

Page 11: Network Programming

/** * This program implements a simple server that listens to port 8189 and echoes back all client

* input. */

Public class EchoServer {

public static void main(String[] args) { try { ServerSocket svrs = new ServerSocket(32112); // wait for client connection Socket s = svrs.accept(); try { InputStream inStream = s.getInputStream(); OutputStream outStream = s.getOutputStream(); Scanner in = new Scanner(inStream);

PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

out.println("Hello! Enter BYE to exit."); // echo client input boolean done = false; while (!done && in.hasNextLine()) { String line = in.nextLine(); out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } } finally { s.close(); } } catch (IOException e) { e.printStackTrace(); } } } Client: import java.io.*; import java.net.*; import java.util.*;

Page 12: Network Programming

/** * This program makes a socket connection to the atomic clock in Boulder, Colorado, and prints the * time that the server sends. */ public class SocketTest { public static void main(String[] args) { try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); try { InputStream inStream = s.getInputStream(); Scanner in = new Scanner(inStream); while (in.hasNextLine()) { String line = in.nextLine(); System.out.println(line); } } finally { s.close(); } } catch (IOException e) { e.printStackTrace(); } } }

Server first creates a socket with the port number and then waits for the client request.

ServerSocket svrs = new ServerSocket(32112); // wait for client connection Socket s = svrs.accept();

Client also creates a socket with the same port number and sends the request to server. Once connection established client and server communicates with each other and when the purpose is over they close the socket on each side.

c) A web server is also called as a Hypertext Transfer Protocol (HTTP) server because it uses HTTP communications with clients and server. For web Server application

Page 13: Network Programming

communicates on port 80. Email server using socket-level programming it will use port 25. On both the server will create port 80 and 25 respectively and start listing to that port. Web Server has two parts after it connects to server one is http request and other is http response. Http request has three components, method-URI-protocol/version, Request headers and Entity body. HTTP response consists of Protocol-Status code-Description, Response headers, Entity body. HTTP request can use several methods as mentioned in the standard some are GET, POST, HEAD, OPTIONS, PUT, DELETE and so on.

Mail server using java, it has some high level API which talks to mail server and sends the mail just because mail server respond to selective request of clients which are trusted.

d) Socket is combination of IP address and port for end point connection. High level networking uses virtual identifier port for end point connection.

Socket is endpoint to the specific connection. High level networking is connection to provider and requester.

Socket cannot have concurrent connections on same port, high level networking can have concurrent connections.

Question 8

a) Protocol:

1) Server waits for client request on particular port. 2) Client request to server for connection 3) Server reply with the connection acceptance 4) Client acknowledges to server. 5) Server asks for the identity 6) Client reply with cardinalities 7) Server checks in the database for valid client, if no go to step 5 8) Client choose 1 option out of 3 9) Server reply with the appropriate answer. 10) Go to step 8 until client terminates the connection.

b) If balance is not allowed to go below negative then before debiting form account balance is checked against the debiting amount. If it goes in negative give message to client that he cannot debit money beyond certain amount.

c)

d) Multithreading allows programs or a process to run many tasks concurrently. It allows process to run its tasks in parallel mode on a single processor system. Server has many requests then single processor system and many processes to execute in as small time it can. With the help

Page 14: Network Programming

of multithreading server can perform much faster than it can without threading. Java Virtual Machine allows an application to have multiple threads of execution running concurrently. It allows program to be more responsible to the user.

Question 9

Simple: It is designed to be simple and easy for the professional programmer to learn and use. If someone knows the basics of Object-Oriented-Programming (OOP) learning java becomes much easier. It requires very little effort who knows OOP.

Object-Oriented: Java is not designed to be source code compatible with any other language. It allows java to design it from scratch. This design is made the usable approach to objects. Java manage to build balance between “everything is an object” and “stay out of my way”.

Distributed: Java handles TCP/IP protocol so it is completely distributed environment of the Internet. It allowed two different computers to execute methods remotely. Java brings an unparalleled version between client and server programming.

Robust: Java is write once run anywhere and it gives the programmers to write the programs platform independent. Java force programmers to find the mistakes in the program during the building the application and at the same time it frees programmers from many other errors which many occur.

Multi-Threaded: Java is design to meet real world requirements of creating more user friendly programs. To achieve this java enables the multithreading programming. Easy to use approach to multithreading of java allows you to think of specific behavior of your code.

Secure: Java is built on very secure accessing policy where it allows compiling the program without allowing or disturbing the resources on the system where they execute.

Architecture Neutral: The main issue of the java designers was the portability and assurance of code written once on machine and successful execution will allow in future working again on any kind of platform. Since the technology is keep upgrading itself.

Portable: Java code is portable because it generates the byte dependant on JVM not on machine specific.

Scalable: Java is considered scalable because if you consider the EJB architecture and run on an appropriate application server, it includes facilities to transparently cluster and allow the use of multiple instances of the EJB to server requests.

High Performance: Java is designed to work on very low-power CPUS. It has the ability to create cross-platform codes.

Page 15: Network Programming

Dynamic: “Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner.”

Page 16: Network Programming

References

1. http://www.javaworld.com/javaworld/jw-05-1997/jw-05-portability.html

2. http://java.dzone.com/articles/does-write-once-run-anwhere 3. java 2 complete Reference 5th Edition 4. http://docs.oracle.com/javase/tutorial/networking/sockets/index.ht

ml 5. http://onjava.com/pub/a/onjava/2003/04/23/java_webserver.html?

page=1 6. http://www.leepoint.net/notes-

java/data/collections/lists/arraylist.html 7. http://www.javaprogrammingforums.com/cafe/11575-

multithreading-its-importance-java.html 8. Java 2 Complete Reference 5th Edition.

Page 17: Network Programming

II Programming Assignment 1 Report

1. Problem Description

Write a simple program to keep track of videos being borrowed from a video store. Detailed instructions are given below. The task is intended to ensure that you have a good grounding in the basic use of objects in Java.

2. Analysis and Proposed Solution

The basic program allows customers to list the videos available and to borrow them (Ignore returning videos). It records whether a video is on the shelf or on loan, and if it is on loan, the date it is due to be returned. Customers can borrow up to two videos for 3 days.

3. Specification and Requirements

Basic knowledge of Java programming and NetBeans tool to implement the program.

4. Implementation description including the use of any tools to aid the design and development.

Solution is built using the NetBeans tool of Java.

There will be four classes one is videotest class which is the user interface, one will be VedioStore class which will act as a database and control point for whole program, one class will be Customer which will store the customer details and set the due date of video to be borrowed and last but not the least Video class which will store the details of video and set all the variable of the video class.

5. Test Cases

Unit to Test Test data Steps to be executed

Constraint Expected result Actual result

List all video

The list of all video from database

Select L option from the Menu

Menu is shown correctly. Options should work in both lower and upper case. User should allow to enter the

List of all videos from database.

Successful

Page 18: Network Programming

option Borrow Video Option (1)

Check User name and video title against the database.

Select B from the Menu

Customer is able Input the User name and Video Title.

Correct name of customer and video title

Successful

Borrow Video Option (2)

Check user is not allowed to borrow more than one video

Select B from the menu, enter username and video title

Borrowed video should not be greater than 2

You cannot borrow more than two video

Successful

Borrow Video Option (3)

Allow customer to borrow video and display the due date

Select B from the menu, enter the user name and video title

User should be able to borrow video

Video is borrowed and display the due date to user.

Successful

Borrow Video Option (4)

Enter the wrong user name and correct video title

Select B from the menu, enter the user name and video title

Customer is not allowed and ask to type again

Wrong customer name please enter the correct name

Successful

Borrow Video Option (5)

Enter the correct user name and wrong video title

Select B from the menu, enter the user name and video title

Video title is not in the database, enter correct name

Video is not in the database please enter correct video title

successful

6. Conclusions

Video store program basic version is implemented successfully.

Page 19: Network Programming

III. Programming Assignment 2 Report

1. Problem Description Write a networked program to run a game of Janken or paper, stone, scissors. In the basic version a single player (client) plays against an automated server and their moves are relayed via a Socket connection.

2. Analysis and Proposed Solution Two programs must be written JankenServer and JankenClient, possibly relying on additional classes to manage the state of the game. Socket: The first thing the players must do is enter their names. The client and server must setup a connection and exchange this information. Play: the game consists of players choosing one of paper, stone or scissors. Paper beats stone, stone beats scissors and scissors beat paper. If both players makes the same choice there is draw and the play is repeated until one player wins. Publishing Results: The results of each game are published on a web server. This is accomplished simply by the server writing (appending) the win/loose and player name to a local file which happens to lie in the publishable directory of a web server running on the same machine.

3. Specification and Requirements Good knowledge of basic java programming and socket level programming. NetBeans tool to implement the program.

4. Implementation description including the use of any tools to aid the design and development.

The basic program will contain two different programs called JankenServer and JankenClient.

JankenServer will consist of two different files one is JankenServer.java and JankenProtocol.java. JankenServer file will creates a socket and listens to it till the client request comes in. Once the client request comes it passes the control to JankenProtocol class. JankenProtocol class will ask for the user name once the client gives the user name it will ask client to make one of 3 choices paper, rock or scissors. After receiving the user choice it will randomly pic one out three options and matches is it a tie or user wins or server wins. After game finishes it will append the result in to the file.

JankenClient program will create socket and tries to connect to JankenServer with the same socket both side. Once the connection is established it will enter the user name and make one of three choices. The result will be displayed to user and will ask if he wants a rematch.

Page 20: Network Programming

5. Test Cases

Unit to Test Test data Steps to be executed

Constraint Expected result Actual result

Connects to server

Check if connection is made the server

Run JankenServer and then JankenClient program

Socket port number should be same

Connection established

Successful

Enter User name and Make one of three choice

Enter any user name and select one of 3 option

Run JankenServer and then JankenClient program

User should be able to input correctly

Server Reply with the Winner name

Successful

6. Conclusion

Successfully implemented basic program and gained the knowledge of socket programming.

Page 21: Network Programming

Appendix 1: Programming assignment 1

VideoTest.Java

import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ //This class is the user interface on the console. public class VideoTest { public static void main(String[] args) { VideoStore vs = new VideoStore(); Scanner sc = new Scanner(System.in); String menuResponse; //Options for user to select and continue. do { System.out.println("Menu : L-list, B-borrow, Q-quit"); menuResponse = sc.nextLine(); if (menuResponse.equalsIgnoreCase("L")) { vs.listallVideos(); } else if (menuResponse.equalsIgnoreCase("B")) { System.out.println("What is your name?"); String nameResponse = sc.nextLine();//takes the user name System.out.println("WHat us the title of the video you want to borrow?"); String videoResponse = sc.nextLine();// takes the video title to be borrowed. vs.borrow(nameResponse, videoResponse); } } while (!menuResponse.equalsIgnoreCase("Q")); } }

Page 22: Network Programming

VideoStore.java

import java.util.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ public class VideoStore { public ArrayList<Video> VideoList; public ArrayList<Customer> CustomerList; //constructor public VideoStore() { //declaration of the arraylists for video and customers VideoList = new ArrayList<Video>(); CustomerList = new ArrayList<Customer>(); //here am intialising a small number of videos and customers and storing them in the arraylists respectively Video va = new Video(); va.setValue("Iron Man", false,0,0,0); Video vb = new Video(); vb.setValue("SKYFALL", false, 0,0,0); Video vc = new Video(); vc.setValue("The Godfather", false, 0,0,0); Video vd = new Video(); vd.setValue("CovertAffairs", false, 0,0,0); Video ve = new Video(); ve.setValue("Inception", false, 0,0,0); Video vf = new Video(); vf.setValue("The Matrix", false, 0,0,0); VideoList.add(va); VideoList.add(vb); VideoList.add(vc); VideoList.add(vd); VideoList.add(ve); VideoList.add(vf); Customer ca = new Customer(); ca.setCustomerValue("Kavi",1);

Page 23: Network Programming

Customer cb = new Customer(); cb.setCustomerValue("Shailesh",0); Customer cc = new Customer(); cc.setCustomerValue("Dhaval",0); Customer cd = new Customer(); cd.setCustomerValue("Manjari",0); Customer ce = new Customer(); ce.setCustomerValue("Ronak",0); Customer cf = new Customer(); cf.setCustomerValue("Kuldeep",0); CustomerList.add(ca); CustomerList.add(cb); CustomerList.add(cc); CustomerList.add(cd); CustomerList.add(ce); CustomerList.add(cf); } // Methods //This method will list all videos public void listallVideos() { for (Video v : VideoList) { System.out.println(v.getTitle()); } } //This method will check user name and video title and then depending on the chocies it will allow to borrow the video. public void borrow(String name, String title) { boolean cfound = false; boolean vfound = false; for (Customer c : CustomerList) { if (name.equalsIgnoreCase(c.getName())) { cfound = true; System.out.println("Customer found, checking for Video Title...."); while (cfound == true && vfound == false) { for (Video v : VideoList) { if (title.equalsIgnoreCase(v.getTitle())) { vfound = true; System.out.println("Video Title found as well, welcome"); c.borrowVideo(v, c); } } } } } if (cfound == false || vfound == false) {

Page 24: Network Programming

System.out.println("EIther Customer Name or Video Title is entered incorrect"); } } }

Customer.java

import java.util.Date; import java.util.GregorianCalendar; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ public class Customer { public String CustomerName; public int numberOfVideosBorrowed; int year, month, day; //this method will return the customer name public String getName() { return CustomerName; } //this method will return the number of videos customer has borrowed public int getNumber() { return numberOfVideosBorrowed; } //this method will set the number of videos to be borrowed public void setNumner(int numberOfVideo){ numberOfVideosBorrowed += numberOfVideo; } //this method will set the customer class variables. public void setCustomerValue(String name, int number){ CustomerName = name; numberOfVideosBorrowed = number; } //this method will allow the customer to borrow video. public void borrowVideo(Video v, Customer c) { Date currentdate = new Date(); int day,month,year; int num = c.getNumber();

Page 25: Network Programming

boolean avail = v.getbool(); if(num > 2){ System.out.println("You can not borrow more video"); } else if(avail == true){ System.out.println("Video is on Loan Try Other Video"); } else { avail = true; num = 1; v.setbool(avail); c.setNumner(num); v.setDate(); } } }

Video.java

import java.util.Date; import java.util.GregorianCalendar; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ public class Video { //declaring variables. String videoTitle; Boolean onLoan; Date dueDate; int day,month,year; //Methods //This will return the vedio title public String getTitle() { return videoTitle; } //this method will retrun video is on loan or no public Boolean getbool(){ return onLoan; } //This method will return the due date public Date getDate() {

Page 26: Network Programming

return dueDate; } //this method will set the loan variable to true or false. public void setbool(boolean loan){ onLoan = loan; } //this vedio will set the actual due date when customre borrows the video. public void setDate(){ Date currentdate = new Date(); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(currentdate); day = calendar.get(calendar.DATE); day = day + 2; month = calendar.get(calendar.MONTH); month = month + 1; year = calendar.get(calendar.YEAR); System.out.println("Due date:"+ day +"/" + month+"/" +year ); } //This method will set all the values of video class. public void setValue(String title, boolean OnLoan,int year, int month, int day) { videoTitle = title; onLoan = OnLoan; GregorianCalendar calendar = new GregorianCalendar(year, month + 1, day); // GregorianCalendar uses 0 for January dueDate = calendar.getTime(); } //tostring method :method returns a textual representation of an object @Override public String toString() { return "title.:" + this.videoTitle + ",, " + "onloan:" + this.onLoan + ",, " + "Duedate:" + this.dueDate; } }

Page 27: Network Programming

Appendix 2: Programming assignment 2

JankenServer.java

import java.io.*; import java.net.ServerSocket; import java.net.Socket; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ public class JankenServer { ServerSocket serverSocket = null; Socket clientSocket = null; PrintWriter out = null; BufferedReader in = null; String inputLine, outputLine,result; void run() { try { //Creating Server Socket serverSocket = new ServerSocket(38189); //Waiting for Client request. clientSocket = serverSocket.accept(); //Creating Input Output Streams out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); JankenProtocol jp = new JankenProtocol(); outputLine = jp.processInput(null); out.println(outputLine); //Communicating with client while ((inputLine = in.readLine()) != null) { outputLine = jp.processInput(inputLine); out.println(outputLine); if(outputLine.contains("WINS")){ result = outputLine.replace("WANT ANOTHER GAME???", ""); System.out.println(result); } if (outputLine.equals("Bye")) { PrintWriter pgr; try {

Page 28: Network Programming

//Writing result to file pgr = new PrintWriter(new FileWriter("junk.html", true)); pgr.println(result); //pgr.println(outputLine); pgr.close(); } catch (IOException ex) { ex.printStackTrace(); } break; } } } catch (IOException e) { e.printStackTrace(); } finally { try { //closing connection out.close(); in.close(); clientSocket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { JankenServer server = new JankenServer(); //while (true) { server.run(); //} } }

JankenProtocol.java

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /**

Page 29: Network Programming

* * @author Sony */ public class JankenProtocol { private static final int NEWPLAYER = 0; private static final int WAITING = 1; private static final int MAKECHOICE = 2; private static final int STARTGAME = 3; private int state = NEWPLAYER; public String name; public String processInput(String theInput) { String theOutput = null; //Asking for Client name if (state == NEWPLAYER) { theOutput = "Welcome, YOUR NAME PLEASE."; state = WAITING; } else if (state == WAITING) {//Asking if player ready to play the game name = theInput; theOutput = "WELCOME" + " " + theInput + " " + "READY TO PLAY?(YES/NO)"; state = MAKECHOICE; } else if (state == MAKECHOICE) { if (theInput.equalsIgnoreCase("YES")) { theOutput = "choose 1 for rock, 2 for paper, or 3 for scissors:"; state = STARTGAME; } else if (theInput.equalsIgnoreCase("NO")) { theOutput = "Bye"; return theOutput; } else { theOutput = "PLEASE CHOOSE YES/NO"; } } else if (state == STARTGAME) { // generate the random number for the server String ServerChoice; Random randomNum = new Random(); float SC = randomNum.nextFloat() * 1; float serverChoice = (float) (Math.round(SC*100.0)/100.0); if(serverChoice >= 0 && serverChoice <= 0.33){ ServerChoice = "1"; } else if(serverChoice >= 0.34 && serverChoice <= 0.66) { ServerChoice = "2"; } else{

Page 30: Network Programming

ServerChoice ="3"; } boolean verifystring = (theInput.equals("2") || (theInput.equals("1") || (theInput.equals("3")))); if (theInput.isEmpty() || !verifystring) { theOutput = "PLEASE CHO0SE 1,2 0R 3"; } if (theInput.equalsIgnoreCase(ServerChoice)) { theOutput = "ITS A TIE!!! WANT A REMATCH?"; { state = MAKECHOICE; } } else if (theInput.equals("1") && ServerChoice.equals("2")) { theOutput = " SERVER WINS" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } else if (theInput.equals("2") && ServerChoice.equals("1")) { theOutput = name + " WINS" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } else if (theInput.equals("1") && ServerChoice.equals("3")) { theOutput = name + " WIN" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } else if (theInput.equals("3") && ServerChoice.equals("1")) { theOutput = "SERVER WINS" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } else if (theInput.equals("2") && ServerChoice.equals("3")) { theOutput = "SERVER WINS" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } else if (theInput.equals("3") && ServerChoice.equals("2")) { theOutput = name + " WIN" + " " + "WANT ANOTHER GAME???"; state = MAKECHOICE; } } else if (theInput.equalsIgnoreCase("NO")) {

Page 31: Network Programming

theOutput = "Bye"; } return theOutput; } }

JankenClient.java

import java.io.*; import java.net.*; import java.util.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author SONY */ public class JankenClient { Socket requestSocket = null; PrintWriter out = null; BufferedReader in = null; BufferedReader stdIn = null; String serverInput; String userInput; void run() { try { //Creating Client Socket requestSocket = new Socket("127.0.0.1", 38189); //Creating Input Output Stream out = new PrintWriter(requestSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(requestSocket.getInputStream())); stdIn = new BufferedReader(new InputStreamReader(System.in)); //Passing Data to server through Input Output Strea while ((serverInput = in.readLine()) != null) { System.out.println("Server: " + serverInput); if (serverInput.equals("Bye")) { break; } userInput = stdIn.readLine(); if (userInput != null) { System.out.println("Client: " + userInput);

Page 32: Network Programming

out.println(userInput); } } } catch (IOException ioException) { ioException.printStackTrace(); } finally { try { //closing the connection out.close(); in.close(); stdIn.close(); requestSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } public static void main(String[] args) { JankenClient client = new JankenClient(); client.run(); } }