html5-img
1 / 115

Networking with Java

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

faunia
Télécharger la présentation

Networking with Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

  2. Topics • Basics • OOP, I/O, Exceptions • Threads • Sockets • Connection oriented • Connectionless • Cryptography API • Security API • JCA (JCE)

  3. Java Basics

  4. OOP • Data encapsulation • Inheritance • Simple • Multiple • Polymorphism • Parametric • Sub type • Information hiding • Objects and Classes

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

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

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

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

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

  10. Class and MethodAccess Control Modifiers

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

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

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

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

  15. 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); } } }

  16. 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(…)

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

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

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

  20. How to do I/O • import java.io.*; • Open the stream • Use the stream (read, write, or both) • Close the stream

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

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

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

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

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

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

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

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

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

  30. General exception handling • If you write code including methods from which an exception may be thrown, here is an outline of what to do

  31. 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); }}

  32. Java Threads

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

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

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

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

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

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

  39. Example – Sub class public class ThreadExample extends Thread { public void run () { for (int i = 1; i <= 100; i++) { System.out.println(“Thread: ” + i); } } }

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

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

  42. Example - Implementing Runnable public class RunnableExample implements Runnable { public void run () { for (int i = 1; i <= 100; i++) { System.out.println (“Runnable: ” + i); } } }

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

  44. Starting the Threads public class ThreadsStartExample { public static void main (String argv[]) { new ThreadExample ().start (); new Thread(new RunnableExample ()).start (); } }

  45. Ready queue Newly created threads Currently executed thread Scheduling Threads start() I/O operation completes

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

  47. 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); } }

  48. 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(); } }

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

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

More Related