Programming in Java Thread Network programming tsaiwncsie nctu

  • Slides: 98
Download presentation
Programming in Java Thread, Network programming 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw 交通大學資訊

Programming in Java Thread, Network programming 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw 交通大學資訊 程學系

Java Threads Agenda Threads and Multithreading Creating a Thread - extending the Thread class

Java Threads Agenda Threads and Multithreading Creating a Thread - extending the Thread class - implementing the Runnable interface Deadlock and Synchronization in Threads Network Programming - TCP/IP protocols - URL : read/write - Socket programming 交通大學資訊 程學系 蔡文能 第 2頁

Java Threads Thread vs. Process • A thread (執行緒; 線程)is a single stream of

Java Threads Thread vs. Process • A thread (執行緒; 線程)is a single stream of execution within a process. • A process (行程; 執行中的程式)is a program executing in its own address space(位址空間, 例如 0 ~ 65535). • You have been using threads all along. • The main control or execution of all the programs up until now were controlled by a single thread. • What we want to look at is mutlithreading or having multiple threads executing within the same program. 交通大學資訊 程學系 蔡文能 第 3頁

Java Threads Test. Tea. java (1/3) //Test. Tea. java --- by tsaiwn@csie. nctu. edu.

Java Threads Test. Tea. java (1/3) //Test. Tea. java --- by tsaiwn@csie. nctu. edu. tw ///This program demostrates how to use Thread in Java. ///But there are two problems: ///(1) stop() is unsafe. This might crash the program. (多 Run 幾次試試) /// We should tell thread to die by using a flag instead of /// using stop( ) to kill the thread. ///(2)concurrent access to Test. Tea. n might cause synchronization problem. /// Codes access to the same variable should be monitored by using /// a synchronized block to mark as a Critical Section. To use Thread SAFELY, Please See Tea. OK. Java 交通大學資訊 程學系 蔡文能 第 4頁

Java Test. Tea. java (2/3) Threads public class Test. Tea { protected static long

Java Test. Tea. java (2/3) Threads public class Test. Tea { protected static long n = 0; public static void main(String[]x) throws Exception{ Tea t 1 = new Tea(); Coffee t 2 = new Coffee(); t 1. start( ); t 2. start( ); while(true){ Thread. sleep(13); if(n > 10){ t 1. stop( ); t 2. stop( ); break; } } // while System. out. println("Thank you and Bye!"); } } 交通大學資訊 程學系 蔡文能 第 5頁

Java Threads Test. Tea. java (3/3) class Coffee extends Thread { public void run(

Java Threads Test. Tea. java (3/3) class Coffee extends Thread { public void run( ) { while(true){ System. out. println("Drink Coffee "+ ++Test. Tea. n); // yield( ); } } // run } class Tea extends Thread{ public void run( ){ while(true){ System. out. println("Drink Tea "+ ++Test. Tea. n); // yield( ); } } // run } 交通大學資訊 程學系 蔡文能 第 6頁

Java Threads Multitasking and Multithreading • Multitasking: - having more than one program working

Java Threads Multitasking and Multithreading • Multitasking: - having more than one program working at what seems to be at the same time (running concurrently). - The OS assigns the CPU to the different programs in a manner to give the impression of concurrency. - There are two types of multitasking – preemptive and cooperative multitasking. • Multithreading: - extends the idea of multitasking by allowing individual programs to have what appears to be multiple tasks. - Each task within the program is called a thread. 交通大學資訊 程學系 蔡文能 第 7頁

Java Threads How to create Java Thread (1/2) • Java has multithreading built into

Java Threads How to create Java Thread (1/2) • Java has multithreading built into it. • Java provides a Thread class for handling threads. • There are two ways to create Thread objects - creating objects from subclasses of the Java Thread class - implementing the Runnable interface for an object Thread. Subclass Thread. X extends Thread { public void run( ) { //logic for the thread } } Thread. X tx = new Thread. X( ); tx. start( ); 交通大學資訊 程學系 蔡文能 第 8頁

Java Threads How to create Java Thread (2/2) - implementing the Runnable interface for

Java Threads How to create Java Thread (2/2) - implementing the Runnable interface for an object Runnable implements Some. Subclass Runnable. Y implements Runnable { public void run ( ) { //logic for the thread } } Runnable. Y ry = new Runnable. Y(); Thread ty = new Thread(ry); ty. start(); In both methods, the run( ) method should be implemented. 交通大學資訊 程學系 蔡文能 第 9頁

Java Threads Thread Class • The Thread class is part of the java. lang

Java Threads Thread Class • The Thread class is part of the java. lang package. • Using an object of this class, the corresponding thread can be stopped, paused, and resumed. • There are many constructors and methods for this class, we will look at a few of them: - Thread( String n) - creates a new Thread with the name n. - Thread( Runnable target) - creates a new Thread object. - Thread( Threadgroup, Runnable target) This creates a new Thread object in the specified Threadgroup. 交通大學資訊 程學系 蔡文能 第 10頁

Java Threads Methods in Thread Class static methods: active. Count(); current. Thread(); sleep(); yield();

Java Threads Methods in Thread Class static methods: active. Count(); current. Thread(); sleep(); yield(); 交通大學資訊 程學系 蔡文能 instance methods: get. Priority( ); start( ); stop( ); (deprecated) run( ); is. Alive( ); suspend( ); resume( ); join( ); 第 11頁

Java Threads Creating Threads (1/4) • Creating a thread by subclassing the Thread class

Java Threads Creating Threads (1/4) • Creating a thread by subclassing the Thread class • This method will allow only five thread to be started in an object. public class Simple. Thread extends Thread { private int count. Down = 3; private static int thread. Count = 0; private int thread. Number = ++thread. Count; public Simple. Thread( ) { System. out. println("Making" + thread. Number++); } 交通大學資訊 程學系 蔡文能 第 12頁

Java Threads Creating Threads (2/4) public void run( ) { while(true) { System. out.

Java Threads Creating Threads (2/4) public void run( ) { while(true) { System. out. println("Thread " + thread. Number + " (" + count. Down + ") "); if (--count. Down == 0) return; } } public static void main(String[] args) { for (int i = 0; i < 5; i++) new Simple. Thread( ). start( ); System. out. println("All Threads Started"); } } 交通大學資訊 程學系 蔡文能 第 13頁

Java Threads Creating Threads (3/4) • One possible output of ‘Simple. Thread’: Making 1

Java Threads Creating Threads (3/4) • One possible output of ‘Simple. Thread’: Making 1 All Threads Started Making 2 Thread 2(3) Making 3 Thread 2(2) Making 4 Thread 6(3) Making 5 Thread 3(2) Thread 3(3) Thread 2(1) Thread 4(3) Thread 6(2) Thread 4(2) Thread 6(1) Thread 4(1) Thread 3(1) Thread 5(3) Thread 5(2) Thread 5(1) 交通大學資訊 程學系 蔡文能 第 14頁

Java Threads Creating Threads (4/4) • One possible output of ‘Simple. Thread’: Tmain T

Java Threads Creating Threads (4/4) • One possible output of ‘Simple. Thread’: Tmain T 0 T 1 Making 2 All Thread started T 2 T 3 T 4 Making 3 Making 4 Making 5 2(3) 3(3) 4(3) 5(3) 6(3) 2(2) 3(2) 4(2) 5(2) 6(2) 2(1) 3(1) 4(1) 5(1) 6(1) 交通大學資訊 程學系 蔡文能 第 15頁

Java Threads Synchronization in Threads (1/5) • Synchronization is a mechanism to control the

Java Threads Synchronization in Threads (1/5) • Synchronization is a mechanism to control the execution of different threads so that: - when multiple threads access a shared variable, proper execution can be assured. • Java has the synchronized keyword - this can be used to identify a segment of code or method that should be accessible to just a single thread at a time. • Before entering a synchronization region, a thread should obtain the semaphore associated with that region – if it is already taken, then the thread blocks (waits) until the semaphore is released. 交通大學資訊 程學系 蔡文能 第 16頁

Java Threads Synchronization in Threads (2/5) class Account { private int balance = 0;

Java Threads Synchronization in Threads (2/5) class Account { private int balance = 0; synchronized void deposit(int amount) { balance += amount; } } class Customer extends Thread { Account account; Customer(Account account) { this. account = account; } public void run() { try { for (int i = 0; i < 10000; i++) {account. deposit(10); } } 交通大學資訊 程學系 蔡文能 第 17頁

Java Threads Synchronization in Threads (3/5) catch (Exception e) { e. print. Stack. Trace();

Java Threads Synchronization in Threads (3/5) catch (Exception e) { e. print. Stack. Trace(); } } /* run */ } /* Customer */ public class Bank. Demo { private final static int NUMCUSTOMER = 10; public static void main(String args[ ]) { //Create account Account account = new Account(); //Create and start customer threads Customer customer[ ] = new Customer[NUMCUSTOMER]; for (int i = 0; i < NUMCUSTOMER; i++) { customer[i] = new Customer(account); customer[i]. start( ); } 交通大學資訊 程學系 蔡文能 第 18頁

Java Threads Synchronization in Threads (4/5) //Wait for customer threads to complete for (int

Java Threads Synchronization in Threads (4/5) //Wait for customer threads to complete for (int i = 0; i < NUMCUSTOMER; i++) { try { customer[i]. join( ); } catch (Interrupted. Exception e) { e. print. Stack. Trace( ); } } //Display account balance System. out. println(account. get. Balance( ) ); } } 交通大學資訊 程學系 蔡文能 第 19頁

Java Threads Synchronization in Threads (5/5) • In Java, any object with one or

Java Threads Synchronization in Threads (5/5) • In Java, any object with one or more synchronized methods is a monitor. • When threads call a synchronized method, only one thread is let in at a time, the others wait in a queue. • In producer- consumer type applications, consumer threads might find that there is not enough elements to consume • It is the job of the monitor to ensure that the threads that are waiting for the producer are notified once the elements are produced. 交通大學資訊 程學系 蔡文能 第 20頁

Java Threads Thread Communication (1/6) • A thread can temporarily release a lock so

Java Threads Thread Communication (1/6) • A thread can temporarily release a lock so other threads can have an opportunity to execute a synchronized method. • It is because the Object class defined three methods that allow threads to communicate with each other. - - void wait( ) - causes the thread to wait until notified - this method can only be called within a synchronized method. - void wait(long msec) throws Interrupted. Exception - void wait(long msec, int nsec) throws Interrupted. Exception void notify( ) - notifies a randomly selected thread waiting for a lock on this object - can only be called within a synchronized method. void notifyall( ) - notifies all threads waiting for a lock on this object - can only be called within a synchronized method. 交通大學資訊 程學系 蔡文能 第 21頁

Java Threads Thread Communication (2/6) class Producer extends Thread { Queue queue; Producer (Queue

Java Threads Thread Communication (2/6) class Producer extends Thread { Queue queue; Producer (Queue queue) { this. queue = queue; } public void run( ) { int i = 0; while(true) { queue. add(i++); } } } 交通大學資訊 程學系 蔡文能 第 22頁

Java Threads Thread Communication (3/6) class Consumer extends Thread { String str; Queue queue;

Java Threads Thread Communication (3/6) class Consumer extends Thread { String str; Queue queue; Consumer (String str, Queue queue) { this. str = str; this. queue = queue; } public void run( ) { while(true) { System. out. println(str + ": " + queue. remove( ) ); } } } 交通大學資訊 程學系 蔡文能 第 23頁

Java Threads Thread Communication (4/6) class Queue { private final static int SIZE =

Java Threads Thread Communication (4/6) class Queue { private final static int SIZE = 10; int array[ ] = new int[SIZE]; int r = 0; int w = 0; int count = 0; synchronized void add(int i) { //wait while the queue is full while (count == SIZE) { try { wait( ); } catch (Interrupted. Exception ie) { ie. print. Stack. Trace( ); System. exit(0); }} /* add */ 交通大學資訊 程學系 蔡文能 第 24頁

Java Threads Thread Communication (5/6) //Add data to array and adjust write pointer array[w++]

Java Threads Thread Communication (5/6) //Add data to array and adjust write pointer array[w++] = i; if (w >= SIZE) w = 0; //Increment count ++count; //Notify waiting threads notify. All( ); } synchronized int remove( ) { //wait while the queue is empty while (count == 0) { try { wait( ); } catch (Interrupted. Exception ie) { ie. print. Stack. Trace( ); System. exit(0); }} 交通大學資訊 程學系 蔡文能 第 25頁

Java Threads Thread Communication (6/6) //read data from array and adjust read pointer int

Java Threads Thread Communication (6/6) //read data from array and adjust read pointer int element = array[r++]; if (r >= SIZE) r = 0; //Decrement count --count; //Notify waiting threads notify. All( ); return element; }} public class Producer. Consumer { public static void main(String args[ ]) { Queue queue = new Queue( ); new Producer(queue). start( ); new Consumer("Consumer. A", queue). start( ); new Consumer("Consumer. B", queue). start( ); new Consumer("Consumer. C", queue). start( ); }} 交通大學資訊 程學系 蔡文能 第 26頁

Java Threads 藍色的是 deprecated Thread Lifecycle Active JVM Born sleep(time) wake up yield( )

Java Threads 藍色的是 deprecated Thread Lifecycle Active JVM Born sleep(time) wake up yield( ) suspend() start( ) resume() Runnable stop( ) return( ) Blocked wait( ) stop( ) return( ) Dead 交通大學資訊 程學系 蔡文能 notify( ) block on I/O complete 第 27頁

Java Threads Wait/Notify Sequence 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. }

Java Threads Wait/Notify Sequence 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } Lock Object 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 28頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 29頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 30頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 31頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 32頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 33頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 3. produce. Resource() 4. synchronized(lock) 5. lock. notify(); 6. } Producer Thread 第 34頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 35頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 36頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 37頁

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource();

Java Threads Wait/Notify Sequence Lock Object 1. synchronized(lock){ 2. lock. wait(); 9. consume. Resource(); 10. } 3. produce. Resource() 4. synchronized(lock) { 5. lock. notify(); 6. } 7. Reacquire lock 8. Return from wait() Consumer Thread 交通大學資訊 程學系 蔡文能 Producer Thread 第 38頁

Java Threads Scheduling : preemptive vs. nonpreemptive Thread scheduling is the mechanism used to

Java Threads Scheduling : preemptive vs. nonpreemptive Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time A thread-scheduling mechanism is either preemptive or nonpreemptive - Preemptive scheduling – the thread scheduler preempts (pauses) a running thread to allow different threads to execute - Nonpreemptive scheduling – the 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 交通大學資訊 程學系 蔡文能 第 39頁

Java Threads Starvation Nonpreemptive scheduler may cause starvation (runnable threads, ready to be executed,

Java Threads Starvation Nonpreemptive scheduler may cause starvation (runnable threads, ready to be executed, wait to be executed in the CPU a lot of time, maybe even forever) Sometimes, starvation is also called livelock 交通大學資訊 程學系 蔡文能 第 40頁

Java Threads Deadlock • Deadlock is an error that can be encountered in multithreads.

Java Threads Deadlock • Deadlock is an error that can be encountered in multithreads. It occurs when two or more threads wait indefinitely for each other to relinquish locks. - Assume that thread-1 holds a lock on object-1 and waits for a lock on object-2. Thread-2 holds a lock on object-2 and waits for a lock on object-1. - Neither of these threads may proceed. Each waits forever for the other to relinquish the lock it needs. 交通大學資訊 程學系 蔡文能 第 41頁

Java Threads Thread Priority The priority values range from 1 to 10, in increasing

Java Threads Thread Priority The priority values range from 1 to 10, in increasing priority 交通大學資訊 程學系 蔡文能 第 42頁

Java Threads Thread Priority Every thread has a priority When a thread is created,

Java Threads Thread Priority Every thread has a priority When a thread is created, it inherits the priority of the thread that created it The priority can be adjusted subsequently using the set. Priority() method The priority of a thread may be obtained using get. Priority() Priority constants are defined: MIN_PRIORITY=1 MAX_PRIORITY=10 NORM_PRIORITY=5 交通大學資訊 程學系 蔡文能 第 43頁

Java Threads Networking Basics Java network program is in the application layer. Using the

Java Threads Networking Basics Java network program is in the application layer. Using the classes in the java. net package. - Don't need to concern yourself with the TCP and UDP layers. 交通大學資訊 程學系 蔡文能 第 44頁

Java Threads TCP/IP 網路通訊協定 de facto Standard (業界標準) TCP/IP network model Layer Function Application

Java Threads TCP/IP 網路通訊協定 de facto Standard (業界標準) TCP/IP network model Layer Function Application End-user application programs Transport Communication among programs on a net (TCP/UDP) Network Basic communication, addressing, and routing (IP, ICMP) Link(Data Link) Network hardware and device drivers(ARP, RARP) 4. 應用層 , 3. 傳輸層(Transport Layer), 2. 網路層, 1. 鏈結層(Link Layer) Developed in the US for the Department of Defense ARPAnet system and has become a de facto standard used by many vendors. 交通大學資訊 程學系 蔡文能 第 45頁

Java Threads TCP/IP網路通訊協定 Layer 4 arp 3 rlogin, talk, ftp, DNS TCP 2 NFS,

Java Threads TCP/IP網路通訊協定 Layer 4 arp 3 rlogin, talk, ftp, DNS TCP 2 NFS, DNS UDP IP 1 traceroute ICMP ARP, Device Drivers Ethernet Header IP Header TCP Header Application Data Ethernet Trailer ETHERNET FRAME 交通大學資訊 程學系 蔡文能 第 46頁

Java Threads 常見名詞術語 MAC Address IP Address Prot # FQDN DNS Server Gateway Router,

Java Threads 常見名詞術語 MAC Address IP Address Prot # FQDN DNS Server Gateway Router, Switch, Hub - Layer 3 Switch 00 -D 0 -B 7 -25 -3 F-A 8 140. 113. 2. 138 TCP 21 (for FTP) ftp. csie. nctu. edu. tw Domain Name Service 閘道口, LAN與WAN交界口 ==~~ Router tsaiwn@csie. nctu. edu. tw 交通大學資訊 程學系 蔡文能 第 47頁

Java CSMA/CD Threads Carrier Sense Multiple Access with Collision Detection Carrier Sense: can tell

Java CSMA/CD Threads Carrier Sense Multiple Access with Collision Detection Carrier Sense: can tell when another host is transmitting Multiple Access: many hosts on 1 wire Collision Detection: can tell when another host transmits at the same time. 交通大學資訊 程學系 蔡文能 第 49頁

Java Threads OSI 7 -Layer Reference Model 分層負責; 分 合作 上 司 管 下

Java Threads OSI 7 -Layer Reference Model 分層負責; 分 合作 上 司 管 下 司 鋤 頭 管 畚 箕 • It prevents changes in one layer from affecting the other layers, so that they can develop more quickly. OSI ISO Proposed by International Organization for Standardization (ISO) 交通大學資訊 程學系 蔡文能 第 51頁

Java Threads Layers (分層負責) The routines/methods of Layer N will not call Layer N+1.

Java Threads Layers (分層負責) The routines/methods of Layer N will not call Layer N+1. The routines/methods of Layer N typically do call the same layer methods. The routines/methods of Layer N typically do call Layer N-1 methods. The routines/methods of Layer N typically may call Layer N-2, N-3, … methods. 交通大學資訊 程學系 蔡文能 第 52頁

Java Threads Physical Layer (實體層) n 實體層 : 定義網路媒介的型態、連接器的型態、以及通訊訊號的型態 Defines the electrical, mechanical, procedural,

Java Threads Physical Layer (實體層) n 實體層 : 定義網路媒介的型態、連接器的型態、以及通訊訊號的型態 Defines the electrical, mechanical, procedural, and functional specifications for activating, maintaining, and deactivating the physical link between end systems - Voltage levels, timing of voltage changes, physical data rates, maximum transmission distances, physical connectors, and other Think of signals and media tsaiwn@csie. nctu. edu. tw 交通大學資訊 程學系 蔡文能 第 53頁

Java Threads Data Link Layer (資料連結層) Layer 2 creates data frames to send to

Java Threads Data Link Layer (資料連結層) Layer 2 creates data frames to send to Layer 1 On receiving side, takes raw data from Layer 1 and packages into data frames - Data frame is basic unit for network traffic on the wire - Ethernet frame on Ethernet (IEEE 802. 3) Performs Cyclic Redundancy Check (CRC) to verify data integrity Detects errors and discards frames containing errors PDU (Protocol Data Units )at Layer 2 is called a frame The software component that operates at this layer is the NIC driver; the hardware components that operate here include the NIC (網路卡) and switches (交換器) OSI 7 -Layer 的第二層相當於 TCP/IP 的第一層 又稱 MAC Layer (Media Access Control) 交通大學資訊 程學系 蔡文能 第 54頁

Java Threads Encapsulation (封裝) Lower layers add headers (and sometimes trailers) to data from

Java Threads Encapsulation (封裝) Lower layers add headers (and sometimes trailers) to data from higher layers Data Application Transport Header Network Layer Data Header Network Data Link Transport Layer Data Header Link Layer Data Header 交通大學資訊 程學系 蔡文能 Data Trailer 第 55頁

Java Threads Encapsulation Details 1024 -5000 FTP server User process 21 23 telnet server

Java Threads Encapsulation Details 1024 -5000 FTP server User process 21 23 telnet server 7 echo server TCP src port TCP dest port header ICMP UDP 17 1 IGMP Others 2 IP header protocol type x 0806 RARP x 8035 Apple. Talk source addr IP x 0800 Ethernet frame type data TCP 6 ARP Novell dest addr TCP discard 9 server Source Dest. hdr cksum addr data IP data CRC (Ethernet Frame types in hex, others in decimal) 交通大學資訊 程學系 蔡文能 第 56頁

Java Threads Ethernet Frame Structure Octet 就是 8 -bit 的 Byte 網路卡 Sending adapter

Java Threads Ethernet Frame Structure Octet 就是 8 -bit 的 Byte 網路卡 Sending adapter encapsulates IP datagram (or other network layer protocol packet) in Ethernet frame : Preamble Destination Address Source Address Frame Type Frame Data CRC 8 octets 6 octets 2 octets 46 -1500 octets 4 octets 先填對方的 MAC address ( 0800 表示 IP datagram) Preamble: 7 bytes with pattern 1010 followed by one byte with pattern 10101011 used to synchronize receiver, sender clock rates CRC : Cyclic Redundency Check 交通大學資訊 程學系 蔡文能 第 57頁

Java Threads Internet Addressing : IP address, 32 bits (IPV 4) Network identifier (identifying

Java Threads Internet Addressing : IP address, 32 bits (IPV 4) Network identifier (identifying the domain) - Assigned under the authority of ICANN - e. g. 192. 207. 177 for Addison Wesley Longman Host address - Assigned by local authority - e. g. 192. 207. 177. 133 Domain Naming System (DNS) - e. g. www. amazon. com - Top-level domain (TLD): e. g. com. tw, edu. tw, gov. ca, org, net 交通大學資訊 程學系 蔡文能 第 58頁

Java Threads Internet Addressing: host names Host name = mnemonic name ( 注意 mn的

Java Threads Internet Addressing: host names Host name = mnemonic name ( 注意 mn的 m 不發音) - Example: mymachine. aw. com - Domain name = part assigned by a registrar Example: aw. com Top level domain = classification of domain owner - By usage – Example: . com = commercial - By country – Example: . au = Australia - Subdomains and individual machine names Assigned by domain owner Domain owner must run a name server. 交通大學資訊 程學系 蔡文能 第 59頁

Java Threads Name server (Domain Name Service) Maintains a directory containing the mnemonic address

Java Threads Name server (Domain Name Service) Maintains a directory containing the mnemonic address and the corresponding numeric IP address within the domain Responds to requests regarding address information All of the name servers throughout the Internet constitute an Internet-wide directory system When a human requests that a message be sent to a destination given in mnemonic form, this system of name servers converts that mnemonic address into equivalent bit-pattern form Such a task is normally completed in a fraction of a second 交通大學資訊 程學系 蔡文能 第 60頁

Java Threads TCP and UDP TCP (Transport Control Protocol) - Point-to-point communication - Connection-oriented

Java Threads TCP and UDP TCP (Transport Control Protocol) - Point-to-point communication - Connection-oriented - Reliable Guarantee data sent from one end gets to the other end. In the same order it was sent. UDP (User Datagram Protocol) - Point-to-point communication - Not connection-oriented - Sends independent packets of data, called datagrams. No guarantees about arrival and the order. 交通大學資訊 程學系 蔡文能 第 61頁

Java Threads TCP is Connection-Oriented Connection oriented means that a virtual connection is established

Java Threads TCP is Connection-Oriented Connection oriented means that a virtual connection is established before any user data is transferred. If the connection cannot be established the user program is notified. If the connection is ever interrupted - the user program(s) is notified. 交通大學資訊 程學系 蔡文能 第 62頁

Java Threads TCP is Reliable means that every transmission of data is acknowledged by

Java Threads TCP is Reliable means that every transmission of data is acknowledged by the receiver. If the sender does not receive acknowledgement within a specified amount of time, the sender retransmits the data. TCP Header (see next page) - URG, ACK, PSH, RST, SYN, FIN - seqno, ACK seqno, window size 交通大學資訊 程學系 蔡文能 第 63頁

Java Threads TCP -- connection-oriented 3 -way Hand Shaking Client Server SYNx , ACK

Java Threads TCP -- connection-oriented 3 -way Hand Shaking Client Server SYNx , ACK 0 SYNy , ACKx+1 LISTENing SYN_RCVD backlog SYNx+1 , ACKy+1 ESTABLISHED 交通大學資訊 程學系 蔡文能 第 64頁

Java Threads TCP Segment Format 1 byte Source Port Destination Port Sequence Number Request

Java Threads TCP Segment Format 1 byte Source Port Destination Port Sequence Number Request Number (ACK Seqno) offset Reser. Control Window Checksum Urgent Pointer Options (if any) Data 交通大學資訊 程學系 蔡文能 第 65頁

Java Threads UDP Datagram Format Source Port Destination Port Length Checksum Data 8 bytes

Java Threads UDP Datagram Format Source Port Destination Port Length Checksum Data 8 bytes UDP Header Datagram Delivery Connectionless Unreliable 交通大學資訊 程學系 蔡文能 第 66頁

Java Threads IP: Internet Protocol IP Header: 20 ~ 60 bytes - Frame type

Java Threads IP: Internet Protocol IP Header: 20 ~ 60 bytes - Frame type = 0 x 0800 - TOS, identification, flags, TTL, protocol, options, … IP Routing - routing table Subnetting, CIDR, and netmask IP Fragmentation - identification and fragment offset - flags field (“more fragment” , “don’t fragment”) Private IP addresses - 10. 0/8, 172. 16. 0. 0/12, 192. 168. 0. 0/16 Related Commands: - ifconfig, netstat 交通大學資訊 程學系 蔡文能 第 67頁

Java Threads IP Datagram 1 byte VERS HL Service Fragment Length Datagram ID FLAG

Java Threads IP Datagram 1 byte VERS HL Service Fragment Length Datagram ID FLAG Fragment Offset TTL Protocol Header Checksum Source Address Destination Address Options (if any) Data 交通大學資訊 程學系 蔡文能 第 68頁

Java Threads Internet Address (IPv 4 Addresses) Five Classes 0 1 2 3 Class

Java Threads Internet Address (IPv 4 Addresses) Five Classes 0 1 2 3 Class A 0 Class B 1 0 Class C 1 1 0 Class D 1 1 1 0 Class E 1 1 4 8 16 netid 24 31 hostid netid hostid Multicast Address 0 Reserved for Future Use IP Address Format (netid, hostid ) Identifies a network Identifies a host on that network 100000001100 00000101 00011110 Dotted Decimal Notation 交通大學資訊 程學系 蔡文能 128. 12. 5. 30 127. 0. 0. 1 代表任何一台 IP 主機自 第 69頁 己

Java Threads Inter-Process Communication Client-server - One server, many clients - Server must run

Java Threads Inter-Process Communication Client-server - One server, many clients - Server must run continuously - Client initiates communication Peer-to-peer - Two processes communicating as equals - Both as the client and server 交通大學資訊 程學系 蔡文能 第 71頁

Java Threads Ports The computer is identified by its 32 -bit IP address. -

Java Threads Ports The computer is identified by its 32 -bit IP address. - IP uses to deliver data to the right computer on the network. Ports are identified by a 16 -bit number. - TCP and UDP use to deliver the data to the right application. - Only one program can listen on a given TCP port at the same time. - However, many remote hosts can connect to the same remote port. The port numbers ranging from 0 - 1023 are restricted. - They are reserved for use by well-known services such as HTTP and FTP. - On Windows NT, 95 and Macs, any user can listen on any port. 交通大學資訊 程學系 蔡文能 第 72頁

Java Threads Programming in TCP - A server application binds a socket to a

Java Threads Programming in TCP - A server application binds a socket to a specific port. - Registering the server with the system to receive all data destined for that port. - A client can then rendezvous with the server at the server's port. 交通大學資訊 程學系 蔡文能 第 73頁

Java Threads Programming in UDP - The datagram packet contains the port number of

Java Threads Programming in UDP - The datagram packet contains the port number of its destination. - UDP routes the packet to the appropriate application. 交通大學資訊 程學系 蔡文能 第 74頁

Java Threads What Is a URL? URL (Uniform Resource Locator) - A reference (an

Java Threads What Is a URL? URL (Uniform Resource Locator) - A reference (an address) to a resource on the Internet. E. g. , http: //www. gamelan. com: 80/pages/Gamelan. network. html #a 1 ftp: //ftp. csie. nctu. edu. tw/pub/CSIE/course/cs 1/ Host Name The name of the machine on which the resource lives. Filename The pathname to the file on the machine. Port Number The port number to which to connect (optional). Reference A reference to a named anchor within a resource that usually identifies a specific location within a file (optional). 交通大學資訊 程學系 蔡文能 第 75頁

Java Threads Creating a URL Simplest way: URL gamelan = new URL("http: //www. gamelan.

Java Threads Creating a URL Simplest way: URL gamelan = new URL("http: //www. gamelan. com/"); Creating a URL Relative to Another http: //www. gamelan. com/pages/Gamelan. game. html http: //www. gamelan. com/pages/Gamelan. net. html URL gamelan = new URL("http: //www. gamelan. com/pages/"); URL gamelan. Games = new URL(gamelan, "Gamelan. game. html"); URL gamelan. Network = new URL(gamelan, "Gamelan. net. html"); Other URL Constructors new URL("http", "www. gamelan. com", new URL("http: //www. gamelan. com/pages/Gamelan. net. html"); new URL("http", "www. gamelan. com", 80, "pages/Gamelan. network. html"); This creates a URL object for the following URL: http: //www. gamelan. com: 80/pages/Gamelan. network. html 交通大學資訊 程學系 蔡文能 第 76頁

Java Threads Exceptions Malformed. URLException - If the arguments to the constructor refer to

Java Threads Exceptions Malformed. URLException - If the arguments to the constructor refer to a null or unknown protocol. try { URL my. URL = new URL(. . . ) } catch (Malformed. URLException e) { //. . . // exception handler code here //. . . } 交通大學資訊 程學系 蔡文能 第 77頁

Java Threads Parsing a URL get. Protocol - Returns the protocol identifier component of

Java Threads Parsing a URL get. Protocol - Returns the protocol identifier component of the URL. get. Host - Returns the host name component of the URL. get. Port - Returns the port number component of the URL. - If the port is not set, get. Port returns -1. get. File - Returns the filename component of the URL. get. Ref - Returns the reference component of the URL. 交通大學資訊 程學系 蔡文能 第 78頁

Java Threads import java. net. *; import java. io. *; public class Parse. URL

Java Threads import java. net. *; import java. io. *; public class Parse. URL { public static void main(String[] args) throws Exception { URL a. URL = new URL("http: //java. sun. com: 80/docs/books/” + "tutorial/index. html#DOWNLOADING"); System. out. println("protocol = " + a. URL. get. Protocol()); System. out. println("host = " + a. URL. get. Host()); System. out. println("filename = " + a. URL. get. File()); System. out. println("port = " + a. URL. get. Port()); System. out. println("ref = " + a. URL. get. Ref()); } } Result: protocol = http host = java. sun. com filename = /docs/books/tutorial/index. html port = 80 ref = DOWNLOADING 交通大學資訊 程學系 蔡文能 第 79頁

Java Threads Reading Directly from a URL Call the URL's open. Stream() method to

Java Threads Reading Directly from a URL Call the URL's open. Stream() method to get a stream from which you can read the contents of the URL. The open. Stream() method returns a java. io. Input. Stream object. open. Stream() = = = open. Connection(). get. Input. Stream() 交通大學資訊 程學系 蔡文能 第 80頁

Java Threads import java. net. *; import java. io. *; public class URLReader {

Java Threads import java. net. *; import java. io. *; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http: //www. yahoo. com/"); Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( yahoo. open. Stream())); String input. Line; while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); in. close(); } } 交通大學資訊 程學系 蔡文能 第 81頁

Java Threads Setting the Proxy Host (Java Application) - UNIX java -Dhttp. proxy. Host=proxyhost

Java Threads Setting the Proxy Host (Java Application) - UNIX java -Dhttp. proxy. Host=proxyhost [-Dhttp. proxy. Port=port. Number] URLReader - DOS shell (Windows 95/NT) java -Dhttp. proxy. Host=proxyhost [-Dhttp. proxy. Port=port. Number] URLReader Setting the Proxy Host (Java Applet) - Follow the setting of your web browser. 交通大學資訊 程學系 蔡文能 第 82頁

Java Threads Connecting to a URL Call the URL object's open. Connection method to

Java Threads Connecting to a URL Call the URL object's open. Connection method to connect to it. URLConnection is an HTTP-centric class. try { URL yahoo = new URL("http: //www. yahoo. com/"); URLConnection yahoo. Connection = yahoo. open. Connection(); } catch (Malformed. URLException e) { // new URL() failed //. . . } catch (IOException e) { // open. Connection() failed. . . } 交通大學資訊 程學系 蔡文能 第 83頁

Java Threads Reading From and Writing to a URLConnection Reading from a URLConnection -

Java Threads Reading From and Writing to a URLConnection Reading from a URLConnection - See next page. Writing to a URLConnection - HTML forms Let you enter data to send to the server. Your Web browser then writes the data to the URL. - A CGI script on the server Receiveing the data, processes it. Then sends you a response, usually in the form of a new HTML page. 交通大學資訊 程學系 蔡文能 第 84頁

Java Threads import java. net. *; import java. io. *; public class URLConnection. Reader

Java Threads import java. net. *; import java. io. *; public class URLConnection. Reader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http: //www. yahoo. com/"); URLConnection yc = yahoo. open. Connection(); Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( yc. get. Input. Stream())); String input. Line; while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); in. close(); } } 交通大學資訊 程學系 蔡文能 第 85頁

Java Threads A Java program can interact with CGI scripts on the server side.

Java Threads A Java program can interact with CGI scripts on the server side. Create a URL. Open a connection to the URL. Set output capability on the URLConnection. Get an output stream from the connection. This output stream is connected to the standard input stream of the cgi-bin script on the server. 5. Write to the output stream. 6. Close the output stream. 1. 2. 3. 4. 交通大學資訊 程學系 蔡文能 第 86頁

Java Threads import java. net. *; import java. io. *; public class Reverse {

Java Threads import java. net. *; import java. io. *; public class Reverse { public static void main(String[] args) throws. Exception { if (args. length != 1) { System. err. println("Usage: java Reverse " + "string_to_reverse"); System. exit(1); } String string. To. Reverse = URLEncoder. encode(args[0]); URL url = new URL("http: //java. sun. com/cgi-bin/backwards"); URLConnection connection = url. open. Connection(); //2 connection. set. Do. Output(true); //3 Print. Writer out = new Print. Writer(connection. get. Output. Stream()); out. println("string=" + string. To. Reverse); //5 out. close(); //6 交通大學資訊 程學系 蔡文能 //1 //4 第 87頁

Java Threads Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( connection.

Java Threads Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader( connection. get. Input. Stream())); String input. Line; while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); in. close(); } } 交通大學資訊 程學系 蔡文能 第 88頁

Java Threads What Is a Socket? A server runs on a computer. - It

Java Threads What Is a Socket? A server runs on a computer. - It has a socket that is bound to a port number. The client tries to rendezvous with the server. - On the server's machine and port. The server accepts the connection. - Upon acceptance, the server gets a new socket bound to a different port. 交通大學資訊 程學系 蔡文能 第 89頁

Java Threads Sever - client communication • A socket can be considered as a

Java Threads Sever - client communication • A socket can be considered as a connection point. port 1 SEVER: port. N …. . . IP address IPc Sockets(Ipc, Port’s. M, port 1) Socketc(Ips, Port 1, port’M) …. . . CLIENT: Port’ 1 交通大學資訊 程學系 蔡文能 Port’M 第 90頁

Java Threads Reading from and Writing to a Socket The client in a client-server

Java Threads Reading from and Writing to a Socket The client in a client-server architecture 1. 2. 3. 4. 5. - Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close the streams. Close the socket. Only step 3 differs from client to client, depending on the server. 交通大學資訊 程學系 蔡文能 第 91頁

Java Threads import java. net. *; import java. io. *; public class Echo. Client

Java Threads import java. net. *; import java. io. *; public class Echo. Client { public static void main(String[] args) throws IOException { Socket echo. Socket = null; Print. Writer out = null; Buffered. Reader in = null; try { echo. Socket = new Socket("taranis", 7); //1 out = new Print. Writer(echo. Socket. get. Output. Stream(), true); //2 in = new Buffered. Reader( new Input. Stream. Reader(echo. Socket. get. Input. Stream())); } catch (Unknown. Host. Exception e) { System. err. println("Don't know about host: taranis. "); System. exit(1); } catch (IOException e) { System. err. println("Couldn't get I/O for " + "the connection to: taranis. "); System. exit(1); } 交通大學資訊 程學系 蔡文能 第 92頁

Java Threads Buffered. Reader std. In = new Buffered. Reader( new Input. Stream. Reader(System.

Java Threads Buffered. Reader std. In = new Buffered. Reader( new Input. Stream. Reader(System. in)); String user. Input; while ((user. Input = std. In. read. Line()) != null) { out. println(user. Input); System. out. println("echo: " + in. read. Line()); } out. close(); //4 in. close(); //4 std. In. close(); echo. Socket. close(); //3 //5 } } 交通大學資訊 程學系 蔡文能 第 93頁

Java Threads Writing the Server Side of a Socket java. net. Socket for client

Java Threads Writing the Server Side of a Socket java. net. Socket for client side. java. net. Server. Socket for server side. try { server. Socket = new Server. Socket(4444); } catch (IOException e) { System. out. println("Could not listen on port: 4444"); System. exit(-1); } 交通大學資訊 程學系 蔡文能 第 94頁

Java Threads Socket client. Socket = null; try { client. Socket = server. Socket.

Java Threads Socket client. Socket = null; try { client. Socket = server. Socket. accept(); } catch (IOException e) { System. out. println("Accept failed: 4444"); System. exit(-1); } • The accept method waits until – A client starts up and requests a connection on the host and port of this server. • When a connection is established – the accept method returns a new Socket object which is bound to a new port. 交通大學資訊 程學系 蔡文能 第 95頁

Java Threads Print. Writer out = new Print. Writer(client. Socket. get. Output. Stream(), true);

Java Threads Print. Writer out = new Print. Writer(client. Socket. get. Output. Stream(), true); Buffered. Reader in = new Buffered. Reader( new Input. Stream. Reader(client. Socket. get. Input. Stream())); String input. Line, output. Line; // initiate conversation with client Knock. Protocol kkp = new Knock. Protocol(); output. Line = kkp. process. Input(null); out. println(output. Line); while ((input. Line = in. read. Line()) != null) { output. Line = kkp. process. Input(input. Line); out. println(output. Line); if(output. Line. equals("Bye. ")) break; } 交通大學資訊 程學系 蔡文能 第 96頁

Java Threads This code: • Gets the socket's input and output stream and opens

Java Threads This code: • Gets the socket's input and output stream and opens readers and writers on them. • Initiates communication with the client by writing to the socket (shown in bold). • Communicates with the client by reading from and writing to the socket (the while loop). 交通大學資訊 程學系 蔡文能 第 97頁

Java Threads and Networking in Java 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ 蔡文能

Java Threads and Networking in Java 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ 蔡文能 交通大學資訊 程學系 蔡文能 第 98頁