JAVA Programming MCA 205 UNIT 2 Bharati Vidyapeeths

JAVA Programming MCA 205 UNIT 2 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof. BVICAM U 2. 1

Learning Objectives • Exception Handling: Fundamentals exception types, uncaught exceptions, throw, final, built in exception, creating your own exceptions, • Multithreaded Programming: Fundamentals, Java thread model: priorities, synchronization, messaging, thread classes, Runnable interface, inter thread Communication, suspending, resuming and stopping threads. • Input/Output Programming: Basics, Streams, Byte and Character Stream, predefined streams, Reading and writing from console and files. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 2

Learning Objectives • Using Standard Java Packages (lang, util, io, net). Networking: Basics, networking classes and • interfaces, using java. net package, doing TCP/IP and Data-gram Programming, RMI (Remote • Method Invocation). © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 3

Types Of Errors Syntax Taken care by Compiler Runtime Linker Taken care by appropriate paths Exceptions Responsibility of Programmer © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 4

Errors vs. Exception • An Error “indicates serious problems that a reasonable application should not try to catch. ” • An Exception “indicates conditions that a reasonable application might want to catch. ” © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 5

Error • Describe internal error • Exceptions of the type Error are caused by Java run-time environment § Outof. Memory. Error § subclasses Assertion. Error of the java. lan. Error class is used by the Java assertion facility. § Other subclasses define exceptions that indicate class linkage (Linkage Error), thread(Thread. Death) and virtual machine (Virtual. Machine. Error) related problems. • These are invariably never explicitly caught and are usually irrecoverable • Consider as unchecked Exception © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 6

Exception Types • There are two types of exceptions in class Exception: 1. Checked exceptions ü When you call a method that throws a checked exception, you must tell the compiler what you are going to do about the exception if it is ever thrown. 2. Unchecked exceptions ü The compiler does not require you to keep track of unchecked exceptions. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 7

Checked vs. Unchecked Exception • Checked Exceptions are the exceptions that are checked at compile time. • If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. • Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. • In Java, exceptions under Error and Runtime. Exception classes are unchecked exceptions, everything else under throwable is checked. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 8

Exception Types. . • Subclasses of Error & Runtime. Exception are unchecked expections • All other subclasses of the class Exception are checked. • Exceptions inherit from Runtime. Exception include § A bad cast § An out-of-bounds array access § A null pointer access • Exceptions not inherit from Runtime. Exception include § Trying to read past the end of file § Example üIOException üAWTException üSQLException © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 9

Exception Class Hierarchy Exception – Except Runtime. Exception Should be caught Error - Not to be caught RTE - can be avoided by programmer Object Throwable Error Exception IOException Arithmetic. Exception Runtime. Exception Array. Index. Out. Of. Bounds. Exception © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 10

Exception Hierarchy © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 11

Built-in Exceptions © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 12

Exception Handling • A Java exception is an object that describes an error condition occurred in the code. • When an exception occurs § An object representing that exception is created and thrown in the method that caused the exception. § That method may choose to handle the exception itself, or pass it on. § At some point, the exception is caught and processed © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 13

Exception Handling • Form of error trapping • Dealing with errors § Return to safe state and enable the user to execute other commands § Allow the user to save all work and terminate the program gracefully • Objective is to transfer control from where the error occurred to an error handler that can deal with the situation. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 14

Handling Runtime Errors Error Codes Non-OO If ( fun 1( ) == ERROR_VALUE ) // handle the error else // do normal things if ( fun 2( ) == NULL ) // handle the error else // do normal things if ( fun 3( ) == -1 ) // handle the error else // do normal things Exceptions OO Too many if-else Difficult to monitor return values in deeply nested calls © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 15

Catching Exceptions • Every exception should be handled somewhere in your program. • If an exception has no handler, an error message is printed, and your program terminates. • In a method that is ready to handle a particular exception type, § place the statements that can cause the exception inside a try block § place the handler inside a catch clause • If you call a method that throw a checked exception, you must either handle it or pass it on. • Catching Multiple Exception § Use a separate catch clause for each type © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 16

1. Exception Handling Syntax try { // Code which might throw an exception //. . . } catch(File. Not. Found. Exception x) //catch(<exceptiontype><parameter 1>) { // code to handle a File. Not. Found exception } catch(IOException x) { // code to handle any other I/O exceptions } catch(Exception x) { // Code to catch any other type of exception } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 17

1. Exception Handling Syntax • Displaying exception description: - Throwable overrides the to. String( ) method (defined by Object) so that it returns a string containing a description of the exception catch (Arithmetic. Exception e) { System. out. println("Exception: " + e); a = 0; // set a to zero and continue } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 18

2. Declaring Checked Exceptions • Majority of the checked exceptions occur when dealing with input and output. • Add a throws specifier to a method that can throw a checked exception. public void File. Input. Stream(String name) throws File. Not. Found. Exception • Multiple exceptions can be separated by commas. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 19

2. Declaring Checked Exceptions • When to use throws § Call a method that throws a checked exception, for example, the File. Input. Stream constructor § Detect an error and throw a checked exception, with the throw statement § Make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as Array. Index. Out. Of. Bounds. Exception. § An internal error occurs in the virtual machine or runtime library • If method fails to faithfully declare all checked exceptions, the compiler will issue an error message © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 20

3. Throwing Exceptions • Program can throw an exception explicitly, using the throw üthrow Throwable. Instance; • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 21

3. Throwing Exceptions • Throwing an Exception § Find an appropriate exception class § Make an object of that class § Throw it. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 22

finally Clause • The finally construct is used to handle a situation in which some action has to be taken whether or not an exception is thrown. Buffered. Reader in= null; try { in = new Buffered. Reader(new File. Reader(filename)); purse. read(in); } finally { if (in != null) in. close(); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 23

finally Clause. . • finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. • Use the finally clause whenever you need to do code cleanup • The finally block will execute whether or not an exception is thrown. • The code in the finally block is executed whenever the try block is exited through any of the next three ways. 1. The code throws no exception 2. The code throws an exception 3. The code throws an exception that is not caught in any catch clause • Finally will not be executed always! © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 24

Custom Exceptions • Java provides us facility to create our own exceptions which are basically derived classes of Exception. • If none of the standard types describes your particular error condition well enough, then design your own exception class. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 25

Multi Threading © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 26

Multithreading • Multithreading is a specialized form of multitasking. • There are two distinct types of multitasking: üProcess based üThread-based. • A process is, in essence, a program that is executing. • Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. • For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 27

Multithreading • In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. • For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads. • Process-based multitasking deals with the “big picture, ” and thread-based multitasking handles the details. • Multitasking threads require less overhead than multitasking processes. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 28

Multithreading • A multithreaded program contains two or more parts that can run concurrently. • Each part of such a program is called a thread, and each thread defines a separate path of execution. • Each thread is a statically ordered sequence of instructions. • Threads are being extensively used express concurrency on both single and multiprocessors machines. • Default thread of the application- main thread. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 29

Multithreading is similar to multi-processing A multi-processing Operating System can run several processes at the same time Each process has its own address/memory space The OS's scheduler decides when each process is executed Only one process is actually executing at any given time. However, the system appears to be running several programs simultaneously Separate processes to not have access to each other's memory space Many OSes have a shared memory system so that processes can share memory space • In a multithreaded application, there are several points of execution within the same memory space. • Each point of execution is called a thread • Threads share access to memory © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 30

A single threaded program class ABC { …. public void main(. . ) { …. . } begin body end } 31 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 31

A Multithreaded Program Main Thread start Thread A start Thread B start Thread C Threads may switch or exchange data/results © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 32

A Multithreaded Program © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 33

Why use Multithreading? In a single threaded application, one thread of execution must do everything If an application has several tasks to perform, those tasks will be performed when the thread can get to them. A single task which requires a lot of processing can make the entire application appear to be "sluggish" or unresponsive. • In a multithreaded application, each task can be performed by a separate thread If one thread is executing a long process, it does not make the entire application wait for it to finish. • If a multithreaded application is being executed on a system that has multiple processors, the OS may execute separate threads simultaneously on separate processors. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 34

Multithreaded Server: For Serving Multiple Clients Concurrently Server Process Client 1 Process Server Threads n Internet Client 2 Process 36 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 36

Modern Applications need Threads (ex 1): Editing and Printing documents in background. Printing Thread Editing Thread 37 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 37
![Multithreaded/Parallel File Copy reader() { - - - - lock(buff[i]); read(src, buff[i]); unlock(buff[i]); - Multithreaded/Parallel File Copy reader() { - - - - lock(buff[i]); read(src, buff[i]); unlock(buff[i]); -](http://slidetodoc.com/presentation_image_h2/34cc08b54b4cf2ce36707afa54183285/image-37.jpg)
Multithreaded/Parallel File Copy reader() { - - - - lock(buff[i]); read(src, buff[i]); unlock(buff[i]); - - - - } buff[0] buff[1] writer() { - - - - - lock(buff[i]); write(src, buff[i]); unlock(buff[i]); - - - - - } Parallel Synchronized Threads 38 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 38

How does it all work? Each thread is given its own "context" A thread's context includes virtual registers and its own calling stack • • The "scheduler" decides which thread executes at any given time The VM may use its own scheduler Since many OSes now directly support multithreading, the VM may use the system's scheduler for scheduling threads The scheduler maintains a list of ready threads (the run queue) and a list of threads waiting for input (the wait queue) Each thread has a priority. The scheduler typically schedules between the highest priority threads in the run queue Note: the programmer cannot make assumptions about how threads are going to be scheduled. Typically, threads will be executed differently on different platforms. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 40

Thread States © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 41

Thread Creation Threads can be created by using two mechanisms : 1. Extending the Thread class • We create a class that extends the java. lang. Thread class. • This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. • We create an object of our new class and call start() method to start the execution of a thread. • Start() invokes the run() method on the Thread object. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 42

Thread Creation 2. Implementing the Runnable Interface • We create a new class which implements java. lang. Runnable interface and override run() method. • Then we instantiate a Thread object and call start() method on this object. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 43

Thread Class vs. Runnable 1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes. 2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 44

Polling • The process of testing a condition repeatedly till it becomes true is known as polling. • Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, certain action is taken. This waste many CPU cycles and makes the implementation inefficient. For example, in a classic queuing problem where one thread is producing data and other is consuming it. • Java’s Solution: § To avoid polling, Java uses three methods, namely, wait(), notify() and notify. All(). All these methods belong to object class as final so that all classes have them. They must be used within a synchronized block only. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 45

Polling Solutions • wait()-It tells the calling thread to give up the lock and go to sleep until some other thread enters the same monitor and calls notify(). • notify()-It wakes up one single thread that called wait() on the same object. It should be noted that calling notify() does not actually give up a lock on a resource. • notify. All()-It wakes up all the threads that called wait() on the same object. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 46

Thread Priority • In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (NORM_PRIORITY) and they are served using FCFS policy. § Java allows users to change priority: üThread. Name. set. Priority(int. Number) MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY=10 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 47

Context Switching • Thread priorities are integers that specify the relative priority of one thread to another. • As an absolute value, a priority is meaningless; a higherpriority thread doesn’t run any faster than a lower-priority thread if it is the only thread running. • Instead, a thread’s priority is used to decide when to switch from one running thread to the next. • This is called a context switch. • Rules: § A thread can voluntarily relinquish control. § A thread can be preempted by a higher-priority thread. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 48

Thread Priority Example class A extends Thread { public void run() { System. out. println("Thread A started"); for(int i=1; i<=4; i++) { System. out. println("t From Thread. A: i= "+i); } System. out. println("Exit from A"); } } class B extends Thread { public void run() { System. out. println("Thread B started"); for(int j=1; j<=4; j++) { System. out. println("t From Thread. B: j= "+j); } System. out. println("Exit from B"); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM } U 2. 49

Thread Priority Example class C extends Thread { public void run() { System. out. println("Thread C started"); for(int k=1; k<=4; k++) { System. out. println("t From Thread. C: k= "+k); } System. out. println("Exit from C"); } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 50
![Thread Priority Example class Thread. Priority { public static void main(String args[]) { A Thread Priority Example class Thread. Priority { public static void main(String args[]) { A](http://slidetodoc.com/presentation_image_h2/34cc08b54b4cf2ce36707afa54183285/image-49.jpg)
Thread Priority Example class Thread. Priority { public static void main(String args[]) { A thread. A=new A(); B thread. B=new B(); C thread. C=new C(); thread. C. set. Priority(Thread. MAX_PRIORITY); thread. B. set. Priority(thread. A. get. Priority()+1); thread. A. set. Priority(Thread. MIN_PRIORITY); System. out. println("Started Thread A"); thread. A. start(); System. out. println("Started Thread B"); thread. B. start(); System. out. println("Started Thread C"); thread. C. start(); System. out. println("End of main thread"); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM } U 2. 51

Yield() and Sleep() yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should run. Otherwise, the current thread will continue to run. Thread. yield(); sleep(): This method causes the currently executing thread to sleep for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Thread. sleep(1000); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 52

Concurrency • An object in a program can be changed by more than one thread • Q: Is the order of changes that were preformed on the object important? © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 53

Race Condition • A race condition – the outcome of a program is affected by the order in which the program's threads are allocated CPU time • Two threads are simultaneously modifying a single object • Both threads “race” to store their value © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 54

Race Condition Example Put green pieces How can we have alternating colors? Put red pieces © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 55

Synchronization • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. • The process by which this is achieved is called synchronization. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 56

Monitors • Key to synchronization is the concept of the monitor (also called a semaphore). • A monitor is an object that is used as a mutually exclusive lock, or mutex. • Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. • These other threads are said to be waiting for the monitor. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 57

Synchronization in Java • To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. • While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. § Therefore, it is within synchronized methods that critical data is updated © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 58

Synchronized Statements • A monitor can be assigned to a block: synchronized(object) { some-code } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 59

An Efficient Approach • We do not always have to synchronize a whole method. • Sometimes it is preferable to synchronize only part of a method. • Java synchronized blocks inside methods makes this possible. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 60

An Efficient Approach class Sender catch (Exception e) { { public void send(String msg) { System. out. println("Thread interrupted. "); } synchronized(this) { System. out. println("Sending t" + msg ); System. out. println("n" + msg + "Sent"); } } try } { Thread. sleep(1000); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 61

Block Synchronization public class Savings. Account { private float balance; public void withdraw(float an. Amount) { if (an. Amount<0. 0) throw new Illegal. Argument. Exception("Withdraw amount negative"); synchronized(this) { if (an. Amount<=balance) balance = balance - an. Amount; } } public void deposit(float an. Amount) { if (an. Amount<0. 0) throw new Illegal. Argument. Exception("Deposit amount negative"); synchronized(this) { balance = balance + an. Amount; } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 62

Static Synchronized Methods • In general, synchronized methods are used to protect access to resources that are accessed concurrently. • When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized instance method; when the resource belongs to all instances (i. e. when it is in a static variable) then you use a synchronized static method to access it. • Marking a static method as synchronized, associates a monitor with the class itself. • The execution of synchronized static methods of the same class is mutually exclusive. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 63

Deadlocks • In multitasking, deadlock occurs when two threads have a circular dependency on a pair of synchronized objects. • For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 64

Deadlocks © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 65

Avoiding Deadlocks • Avoid Nested Locks : This is the main reason for dead lock. Dead Lock mainly happens when we give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to one. • Avoid Unnecessary Locks : We should have lock only those members which are required. Having lock on unnecessarily can lead to dead lock. • Using thread join : Dead lock condition appears when one thread is waiting other to finish. If this condition occurs we can use Thread. join with maximum time you think the execution will take. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 66

Livelocks • A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. • As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. • This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 67

Streams & Files © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 68

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)” • Stream is an abstraction that either produces or consumes information. • Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. • Output stream may refer to the console, a disk, file, or a network connection. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 69

Java I/O • Java I/O is based around the concept of a stream § Ordered sequence of information (bytes) coming from a source, or going to a ‘sink’ Input. Stream § Simplest stream reads/writes only a single byte, or an array of bytes at a time Output. Stream • Designed to be platform-independent • The stream concept is very generic § Can be applied to many different types of I/O § Files, Network, Memory, Processes, etc © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 70

Java I/O © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 71

Java. io • The java. io package contains all of the I/O classes. § Many classes specialised for particular kinds of stream operations, e. g. file I/O • Reading/writing single bytes is quite limited § So, it includes classes which provide extra functionality § e. g. buffering, reading numbers and Strings (not bytes), etc. • Results in large inheritance hierarchy, with separate trees for input and output stream classes © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 72

Byte. Stream • Byte streams provide a convenient means for handling input and output of bytes. • Byte streams are used, for example, when reading or writing binary data. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 74

Byte. Stream © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 75

Byte. Stream • Input. Stream (abstract class) § File. Input. Stream § Filter. Input. Stream üBuffered. Input. Stream üData. Input. Stream § Object. Input. Stream • Output. Stream (abstract class) § File. Output. Stream § Filter. Output. Stream üBuffered. Output. Stream üData. Input. Stream § Object. Output. Stream © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 76

Character Stream • Character streams provide a convenient means for handling input and output of characters. • They use Unicode and, therefore, can be internationalized. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 77

Character Stream © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 78

Character Stream • Reader (abstract class) § Buffered. Reader § Input. Stream. Reader üFile. Reader • Writer (abstract class) § Buffered. Writer § Output. Stream. Writer üFile. Writer § Print. Writer © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 79

Steps to do I/O import java. io. *; • Open the stream • Use the stream (read, write, or both) • Close the stream © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 80

Combining Stream Filters • File. Input. Stream has no method to read numeric types, • Data Input. Stream has no method to get data from a file • Read bytes and assemble bytes into more useful data types Data. Input. Stream din = new Data. Input. Stream(new File Input. Stream(“temp. txt”)); Data. Input. Stream din = new Data. Input. Stream(new Buffered. Input. Stream( new File Input. Stream(“temp. txt”))); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 81

Character Stream use Byte Stream • Character streams are often "wrappers" for byte streams. T • character stream uses the byte stream to perform the physical I/O, • while the character stream handles translation between characters and bytes. § File. Reader uses File. Input. Stream § File. Writer uses File. Output. Stream • Two general-purpose byte-to-character "bridge" streams: § Input. Stream. Reader § Output. Stream. Writer. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 82

Line-Oriented I/O • Two Classes üBuffered Reader üPrint. Writer Buffered. Reader input. Stream = null; Print. Writer output. Stream = null; input. Stream = new Buffered. Reader(new File. Reader(“temp. txt")); output. Stream = new Print. Writer(new File. Writer("output. txt")); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 83

Buffered Streams • Unbuffered I/O make a program much less efficient • Each such request often triggers disk access, network activity, or some other operation that is relatively expensive • To reduce overhead, the Java platform implements buffered I/O streams • Program can convert an unbuffered stream into a buffered stream using the wrapping idiom input. Stream = new Buffered. Reader(new File. Reader("xanadu. txt")); output. Stream = new Buffered. Writer(new File. Writer("characteroutput. txt")); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 84

Writing & Reading Object in Files • To write. Object State § To write data in binary format Data. Output. Stream with File. Output. Stream § To write in text Format use Print. Writer with File. Writer • To read. Object State § To read data in binary format Data. Inut. Stream with File. Input. Stream § To read in text Format use Scanner class © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 85

Random Access Files • • Random. Access. File Find or write data anywhere in a file Implements Data. Input and Data. Output interface Has file pointer Use method seek & get. File. Pointer © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 86

Serialization • Serialization is a mechanism of converting the state of an object into a byte stream. • Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. • To make a Java object serializable we implement the java. io. Serializable interface. § The Object. Output. Stream class contains write. Object() method for serializing an Object. § The Object. Input. Stream class contains read. Object() method for deserializing an object. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 87

Object Streams and Serialization • Object serialization--Java's built-in mechanism for manipulating objects as streams of bytes. • serialized object is an object represented as a sequence of bytes that includes § the object’s data § information about the object’s type § the types of data stored in the object. • After a serialized object has been written into a file, it can be read from the file and deserialized § the type information and bytes that represent the object and its data can be used to recreate the object in memory. • Object serialization is performed with byte-based streams, so the sequential files created and manipulated will be binary files • Need to tag fields as transient if belong to non-serializable classes © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 88

Object Streams and Serialization © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 89

Marker Interface • Serializable is a marker interface (has no data member and method). • It is used to “mark” java classes so that objects of these classes may get certain capability. • Other examples of marker interfaces are: - Cloneable and Remote. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 90

Serial. Version. UID • The Serialization runtime associates a version number with each Serializable class called a Serial. Version. UID, which is used during Deserialization to verify that sender and reciever of a serialized object have loaded classes for that object which are compatible with respect to serialization. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 91

Rules of Serialization • If a parent class has implemented Serializable interface then child class doesn’t need to implement it but viceversa is not true. • Only non-static data members are saved via Serialization process. • Static data members and transient data members are not saved via Serialization process. • Constructor of object is never called when an object is deserialized. • Associated objects must be implementing Serializable interface. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 92

Externalizable Interface • Externalization serves the purpose of custom Serialization, where we can decide what to store in stream. • Externalizable interface present in java. io, is used for Externalization which extends Serializable interface. • It consist of two methods which we have to override to write/read object into/from stream which areü// to read object from stream void read. External(Object. Input in) ü// to write object into stream void write. External(Object. Output out) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 93

NETWORKING © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 94

Client/Server Computing • Communication over the network often occurs between a client and a server • A client connects to a server and then sends and receives messages • A server waits for connection requests from clients, accepts them, and then responds to their messages • TCP/IP: abstract layer that simplifies the above activities © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 95

Hosts, Ports, and Sockets • Host – a computer uniquely identified by hostname and/or IP Address § hostname: a String name (e. g. , aegis. ateneo. net) § IP address: a set of 4 bytes (e. g. , 10. 0. 1. 34) § Type ipconfig or winipcfg to check your address • Port – a number that specifies the type of connection you want to make § e. g. , port 80 is for HTTP (web protocol), port 23 is for Telnet (logging in to a UNIX account), etc. § each server can listen to many ports § each port can accommodate many clients • Socket – object that encapsulates the communication process § hides the details of how things work Networking © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 96

Types of Transfer Networks typically provide two types of transfer § Connection-oriented üoften reliable üstream based üPoint to point – like phone call § Connectionless üoften unreliable üdatagram based üSends independent packets of data üOrder of delivery is not important üDelivery not guaranteed © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 97

Types of Transfer § TCP üTransmission Control Protocol üConnection based protocol that provides a üreliable flow of data § UDP üUser Datagram Protocol üSends independent packets of data with no guarantee of arrival © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 98

Networking in Java • java. net package § import java. net. *; • Most important classes § Inet. Address § Connection-oriented Transfer üSocket üServer. Socket § Connection-less Transfer üDatagram. Packet üDatagram. Socket © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 99

Inet. Address • The Inet. Address Class is used to encapsulate both the numerical IP Address and domain name for that address. • Has no visible constructors. Then How To Instantiate? Factory Methods © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 100

Common Factory Methods • static Inet. Address Unknown. Host. Exception get. Localhost() throws • static Inet. Address get. By. Name(String hostname) throws Unknown. Host. Exception • static Inet. Address[ ] get. All. By. Name(String hostname) throws Unknown. Host. Exception • Static Inet. Address get. By. Address(byte[] addr) Unknown. Host. Exception throws © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 101

Checking IP Address Host. Info. java import java. net. *; import java. io. *; import java. util. *; public class Host. Info { public static void main(String args[]) { Inet. Address ip. Addr; try { ip. Addr = Inet. Address. get. Local. Host(); System. out. println("This is "+ip. Addr); } catch (Unknown. Host. Exception e) { System. out. println("Unknown host"); } }} © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 102

Socket Programming with TCP Processes communicating through TCP sockets © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 103

Socket • • A socket represents a TCP connection Reliable Stream oriented – Uses java. io classes Classes: § Server. Socket üPassive, simply waits for client connections § Socket üActive, will initiate connection with server © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 104

Sockets for server and client • Server § Welcoming socket üWelcomes some initial contact from a client. § Connection socket üIs created at initial contact of client. üNew socket that is dedicated to the particular client. • Client § Client socket üInitiate a TCP connection to the server by creating a socket object. üSpecify the address of the server process, namely, the IP address of the server and the port number of the process. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 105

Class Socket • Constructor takes the host and port that the client wants to connect to § public Socket() § public Socket(Inet. Address address, int port); § public Socket(String host, int port); § public void close(); § public Inet. Address get. Inet. Address(); § public int get. Local. Port(); § public int get. Port(); § public String to. String(); § public Input. Stream get. Input. Stream(); § public Output. Stream get. Output. Stream(); • Given these Streams, you can send/receive data • Writing to Output. Stream sends the data to the other host • To read the data, the other host must read from the Input. Stream • You can/should chain other “filter” streams to these before using them – just like you did for files (e. g. , you can use Buffered. Reader, etc. ) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 106

Class Server. Socket • it is-NOT-a Socket § doesn’t extend Socket, and doesn’t have the same methods • actually, it creates sockets, in response to a client connection • maybe better called “Connection. Listener” or “Socket. Server” • Constructor takes port number that the server wishes to listen to • Call the accept() method to accept a client § Thread that calls accept() blocks (waits or “sleeps”) until a client connects § Thread continues after client connects. The accept() method then returns a Socket object connected to the client • public Server. Socket(int port); • public Socket accept(); • public void close(); • public Inet. Address get. Inet. Address(); • public int get. Local. Port(); • public String to. String(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 107

The Socket class • Constructor takes the host and port that the client wants to connect to • Useful Socket methods § Input. Stream get. Input. Stream() § Output. Stream get. Output. Stream() • Given these Streams, you can send/receive data § Writing to Output. Stream sends the data to the other host § To read the data, the other host must read from the Input. Stream § You can/should chain other “filter” streams to these before using them – just like you did for files (e. g. , you can use Buffered. Reader, etc. ) Networking © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM Slide 108 U 2. 108

The Server. Socket class • Misnomer § it is-NOT-a Socket üdoesn’t extend Socket, and doesn’t have the same methods § actually, it creates sockets, in response to a client connection § maybe better called “Connection. Listener” or “Socket. Server” • Constructor takes port number that the server wishes to listen to • Call the accept() method to accept a client § Thread that calls accept() blocks (waits or “sleeps”) until a client connects § Thread continues after client connects. The accept() method then returns a Socket object connected to the client Networking © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 109

Sockets Client socket, welcoming socket and connection socket © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 110

Client/server socket interaction: TCP Server (running on hostid) Client create socket, port=x, for incoming request: welcome. Socket = Server. Socket() TCP wait for incoming connection request connection. Socket = welcome. Socket. accept() read request from connection. Socket write reply to connection. Socket close connection. Socket setup create socket, connect to hostid, port=x client. Socket = Socket() send request using client. Socket read reply from client. Socket close client. Socket © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 111

TCPClient. java import java. io. *; import java. net. *; Import java. util. *; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modified. Sentence; Scanner in. From. User = new Scanner(System. in); Socket client. Socket = new Socket("hostname", 6789); Print. Writer out. To. Server = new Print. Writer(client. Socket. get. Output. Stream(), true); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 112

TCPClient. java Scanner in. From. Server = new Scanner(client. Socket. get. Input. Stream()); sentence = in. From. User. next. Line(); out. To. Server. println(sentence ); modified. Sentence = in. From. Server. next. Line(); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 113

TCPServer. java import java. io. *; import java. net. *; Import java. util. *; class TCPServer { public static void main(String argv[]) throws Exception { String client. Sentence; String capitalized. Sentence; Server. Socket welcome. Socket = new Server. Socket(6789); while(true) { Socket connection. Socket = welcome. Socket. accept(); Scanner in. From. Client = new Scanner( connection. Socket. get. Input. Stream()); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 114

TCPServer. java Print. Writer out. To. Client = new Print. Writer(connection. Socket. get. Output. Stream(), true); client. Sentence = in. From. Client. read. Line(); capitalized. Sentence = client. Sentence. to. Upper. Case() + 'n'; out. To. Client. write. Bytes(capitalized. Sentence); } } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 115

Socket Programming with UDP • UDP § Connectionless and unreliable service. § There isn’t an initial handshaking phase. § Doesn’t have a pipe. § transmitted data may be received out of order, or lost • Socket Programming with UDP § No need for a welcoming socket. § No streams are attached to the sockets. § the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes. § The receiving process must unravel to received packet to obtain the packet’s information bytes. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 116
![Datagram Packet • Represents a datagram packet • Datagram. Packet(byte[] buf, int length, Inet. Datagram Packet • Represents a datagram packet • Datagram. Packet(byte[] buf, int length, Inet.](http://slidetodoc.com/presentation_image_h2/34cc08b54b4cf2ce36707afa54183285/image-114.jpg)
Datagram Packet • Represents a datagram packet • Datagram. Packet(byte[] buf, int length, Inet. Address address, int port) • Datagram. Packet(byte[] buf, int length) • Inet. Address get. Address() • byte[] get. Data(); • int get. Length(); • int get. Port(); • void set. Address(Inet. Address iaddr); • void set. Data(byte[] ibuf); • void set. Length(int ilength); • void set. Port(int iport); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 117

Client/server socket interaction: UDP Server (running on hostid) create socket, port=x, for incoming request: server. Socket = Datagram. Socket() read request from server. Socket write reply to server. Socket specifying client host address, port umber Client create socket, client. Socket = Datagram. Socket() Create, address (hostid, port=x, send datagram request using client. Socket read reply from client. Socket close client. Socket © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 118

JAVA UDP Sockets • In Package java. net § java. net. Datagram. Socket üA socket for sending and receiving datagram packets. üConstructor and Methods Datagram. Socket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. void receive( Datagram. Packet p) void send( Datagram. Packet p) void close() © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 119

UDPClient. java import java. io. *; import java. net. *; class UDPClient { public static void main(String args[]) throws Exception { Scanner in. From. User = new Scanner(System. in); Datagram. Socket client. Socket = new Datagram. Socket(); Inet. Address IPAddress = Inet. Address. get. By. Name("hostname"); byte[] send. Data = new byte[1024]; byte[] receive. Data = new byte[1024]; String sentence = in. From. User. next. Line(); send. Data = sentence. get. Bytes(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 120

UDPClient. java Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, 9876); client. Socket. send(send. Packet); Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); client. Socket. receive(receive. Packet); String modified. Sentence = new String(receive. Packet. get. Data()); System. out. println("FROM SERVER: " + modified. Sentence); client. Socket. close(); } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 121

UDPServer. java import java. io. *; import java. net. *; class UDPServer { public static void main(String args[]) throws Exception { Datagram. Socket server. Socket = new Datagram. Socket(9876); byte[] receive. Data = new byte[1024]; byte[] send. Data = new byte[1024]; while(true) { Datagram. Packet receive. Packet = new Datagram. Packet(receive. Data, receive. Data. length); server. Socket. receive(receive. Packet); String sentence = new String(receive. Packet. get. Data()); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 122

UDPServer. java Inet. Address IPAddress = receive. Packet. get. Address(); int port = receive. Packet. get. Port(); String capitalized. Sentence = sentence. to. Upper. Case(); send. Data = capitalized. Sentence. get. Bytes(); Datagram. Packet send. Packet = new Datagram. Packet(send. Data, send. Data. length, IPAddress, port); server. Socket. send(send. Packet); } } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 123

Handling Multiple Connections • Use Threads • Main Thread § Have a loop that continuously calls accept() § Create and start a new “connection thread” whenever accept() returns a socket • Connection Thread § Thread for talking with 1 client (only) § read, write client via socket’s input and output streams § may have a loop, reading “requests” from client and responding Networking © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 124

Multiple Clients myserver ss connection thread public void run() { // get input streams // read/write client // loop } main thread port 8888 connection thread s while ( true ) { Socket s = ss. accept(); CThread ct = new CThread( s ); ct. start(); } Notes: n main thread just accepts n create and start 1 new thread per client s s client s s s © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Ritika Wason, Associate Prof BVICAM U 2. 125
- Slides: 122