1.17k likes | 1.35k Views
Networking with Java. Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul ). Topics. Basics OOP, I/O, Exceptions Threads Sockets Connection oriented Connectionless Cryptography API Security API JCA (JCE). Java Basics. OOP. Data encapsulation
E N D
Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )
Topics • Basics • OOP, I/O, Exceptions • Threads • Sockets • Connection oriented • Connectionless • Cryptography API • Security API • JCA (JCE)
OOP • Data encapsulation • Inheritance • Simple • Multiple • Polymorphism • Parametric • Sub type • Information hiding • Objects and Classes
Objects and Classes • Class Abstract entity representing structure • Consists of declarations/definitions for variables and methods • Object Instance of a class • Consists of actual data and methods that operate on them • Many instances of the same class • The real data structure on which operations are performed
Java Classes • Java programs are a collection of class declarations • One class in each file with the file having the same name as the class • Each class defines a collection of data and function members
Object in Java – A Class ! • All classes in Java are descendants of the class Object • Class descendency • Trace back through the inheritance chain • All chains lead to the class Object • Object class is default inheritance when not specified
Java Package • Archival of portable objects for reuse • Similar to a “library” • Steps for making/using a package • Make an object “public” • Add “package” statement to object definition • Compile object source code (compiler will store compiled code according to package statement) • Import object into other code via “import” statement
Packages • Methods are grouped within classes • A class is declared to be part of a package using the package keyword • Classes are imported using the import keyword • package srd.math; public class ComplexNumber { private double m_dReal; private double m_dImag; // constructors public ComplexNumber(double dR, double dI){ m_dReal = dR; m_dImag = dI; }
Constructors • A method for creating an instance of a class • Same name as class it is contained in • “NO” return type or return values • Instance variable initialization can be done here • At least one public constructor in every class • Constructors (and all methods) can be overloaded • Default constructor is always a “no argument” • No default constructor is provided if the programmer supplies at least one
Constants using Final • NO change in value through the lifetime of the variable • Similar to the const keyword in C • Variables declared with final • Can be initialized in a constructor, but must be assigned a value in every constructor of the class
Building Composite Objects • Objects with objects as instance variables • Building up complex classes is good object oriented design • Reuse of existing classes • To detect bugs incrementally • Debugging with test drivers as classes are developed
Symbolic Constants • No global constants in Java • Static members of a class give similar functionality • Examples: public final static float PI = 3.1415926; where “final indicates this value cannot be altered • Static variable identifier can be a class • if PI definition above is contained in class Math, it can be referenced as Math.PI
Static Initializers • Sometimes a static data member needs to be initialized too • class BankAccount{ static private int m_nNextAccountNumber = 100001;} • Sometimes initialization requires more steps • class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel;} • Java provides a special construct for this purpose • class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel; static{ for (int i = 0; i < m_nNUMBERCHANNELS; i++){ m_channel[i] = new Channel(i); } } }
Class extension - Inheritance • Classes can be defined as extensions (subclasses) of already-defined classes • Inherits methods,variables from the parent • May contain additional attribute fields • May provide additional functionality by providing new methods • May provide replacement functionality by overriding methods in the superclass • Often, a subclass constructor executes the parent constructor by invoking super(…)
Overloading methods • void fn(TV mytv, Radio myradio){ mytv.ChangeChannel(); // tune the TV myradio.ChangeChannel(); // tune the radio } • Current class assumed when no qualification • Overloading based on different types of arguments • double fn(BankAccount baMyAccount){ baMyAccount.Rate(8.0); // sets the rate return baMyAccount.Rate(); // queries the rate } • No overloading based on return value
this keyword • A class declaration is like a template for making objects • The code is shared by all objects of the class • Each object has its own values for the data members • The object itself is an implicit parameter to each method • In the class declarations, one can use the keyword “this” to refer to the object itself explicitly
Java I/O - Streams • All modern I/O is stream-based • A stream is a connection to a source of data or to a destination for data (sometimes both) • Different streams have different characteristics • A file has a definite length, and therefore an end • Keyboard input has no specific end
How to do I/O • import java.io.*; • Open the stream • Use the stream (read, write, or both) • Close the stream
Why Java I/O is hard • Java I/O is very powerful, with an overwhelming number of options • Any given kind of I/O is not particularly difficult • Buffered • Formatted etc • The trick is to find your way through the maze of possibilities • It’s all about picking the right one
Opening a stream • When you open a stream, you are making a connection to an external entity • The entity to which you wish to write data to or read data from • Streams encapsulate complexity of external entity • Streams also provide flexibility in usage of data – Different types
Example - Opening a stream • A FileReader is a used to connect to a file that will be used for input • FileReader fileReader = new FileReader(fileName); • The fileName specifies where the (external) file is to be found • You never use fileName again; instead, you use fileReader
Using a stream • Some streams can be used only for input, others only for output, still others for both • Using a stream means doing input from it or output to it • But it’s not usually that simple • One needs to manipulate the data in some way as it comes in or goes out
Example of using a stream • int ch;ch = fileReader.read( ); • The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read (EOF) • The meaning of the integer depends on the file encoding (ASCII, Unicode, other)
Closing • A stream is an expensive resource • There is a limit on the number of streams that you can have open at one time • You should not have more than one stream open on the same file • You must close a stream before you can open it again • Always close your streams!
Serialization • You can also read and write objects to files • Object I/O goes by the awkward name of serialization • Serialization can be very difficult • objects may contain references to other objects • Java makes serialization (almost) easy
Conditions for serializability • If an object is to be serialized • The class must be declared as public • Class must implement Serializable • The class must have a no-argument constructor • All fields of the class must be serializable • Either primitive types or serializable objects
Exceptions • Historically, programs would provide a message and halt on errors • Hardly acceptable in today’s interactive environment • In Java, methods “throw” exceptions when such errors occur • Method which invoked the method encountering the error can either “catch” the exception, or pass it up the heirarchy
General exception handling • If you write code including methods from which an exception may be thrown, here is an outline of what to do
Exception Example • package srd.math; import java.lang.Exception; public class ComplexNumber{ // ... other data and methods as before // division operator written to use exceptions public ComplexNumber Divide(double d) throws Exception{ if (d == 0.0){ throw new Exception("Divide by zero in ComplexNumber.divide"); } return new ComplexNumber(m_dReal / d, m_dImag / d); }}
Multitasking v/s Multithreading • Multitasking refers to a computer's ability to perform multiple jobs concurrently • A thread is a single sequence of execution within a program • Multithreading refers to multiple threads of control within a single program • each program can run multiple threads of control within it
Threads - Need • To maintain responsiveness of an application during a long running task • To enable cancellation of separable tasks • Some problems are intrinsically parallel • Some APIs and systems demand it • Swings • Animation
Example - Animation • Suppose you set up Buttons and attach Listeners to those buttons • Then your code goes into a loop doing the animation • Who’s listening ? • Not this code; it’s busy doing the animation • sleep(ms) doesn’t help!
Application Thread • When we execute an application • The JVM creates a Thread object whose task is defined by the main() method • It starts the thread • The thread executes the statements of the program one by one until the method returns and the thread dies
Multiple Threads • Each thread has its private run-time stack • If two threads execute the same method, each will have its own copy of the local variables the methods uses • All threads see the same dynamic memory, heap • Two different threads can act on the same object and same static fields concurrently • Race conditions • Deadlocks
Creating Threads • There are two ways to create our own Thread object • Sub classing the Thread class and instantiating a new object of that class • Implementing the Runnable interface • In both cases the run() method should be implemented
Example – Sub class public class ThreadExample extends Thread { public void run () { for (int i = 1; i <= 100; i++) { System.out.println(“Thread: ” + i); } } }
Thread Methods void start() • Creates new thread and makes it runnable • This method can be called only once void run() • The new thread begins its life inside this method void stop() • The thread is being terminated
Thread Methods (Continued) • yield() • Causes currently executing thread object to temporarily pause and allow other threads to execute • Allows only threads of the same priority to run • sleep(int m)/sleep(int m,int n) • The thread sleeps for m milliseconds, plus n nanoseconds
Example - Implementing Runnable public class RunnableExample implements Runnable { public void run () { for (int i = 1; i <= 100; i++) { System.out.println (“Runnable: ” + i); } } }
Why two mechanisms ? • Java supports simple inheritance • A class can have only one super class • But it can implement many interfaces • Allows threads to run , regardless of inheritance Example – an applet that is also a thread
Starting the Threads public class ThreadsStartExample { public static void main (String argv[]) { new ThreadExample ().start (); new Thread(new RunnableExample ()).start (); } }
Ready queue Newly created threads Currently executed thread Scheduling Threads start() I/O operation completes
Thread State Diagram Alive Running new ThreadExample(); while (…) { … } New Thread Runnable Dead Thread thread.start(); run() method returns Blocked Object.wait() Thread.sleep() blocking IO call waiting on a monitor
Example public class PrintThread1 extends Thread { String name; public PrintThread1(String name) { this.name = name; } public void run() { for (int i=1; i<500 ; i++) { try { sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) { } System.out.print(name); } }
Example (cont) public static void main(String args[]) { PrintThread1 a = new PrintThread1("*"); PrintThread1 b = new PrintThread1("-"); PrintThread1 c = new PrintThread1("="); a.start(); b.start(); c.start(); } }
Scheduling • Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time • Priority is taken into consideration • Thread-scheduling mechanisms • preemptive or • nonpreemptive
Preemptive Scheduling • Preemptive scheduling • Scheduler preempts a running thread to allow different threads to execute • Nonpreemptive scheduling • Scheduler never interrupts a running thread • The nonpreemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute