Presentation is loading. Please wait.

Presentation is loading. Please wait.

交通大學資訊工程學系 Programming in Java Thread, Network programming 蔡文能 交通大學資訊工程學系

Similar presentations


Presentation on theme: "交通大學資訊工程學系 Programming in Java Thread, Network programming 蔡文能 交通大學資訊工程學系"— Presentation transcript:

1

2 交通大學資訊工程學系 Programming in Java Thread, Network programming 蔡文能 交通大學資訊工程學系

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

4 交通大學資訊工程學系 蔡文能 8- 第 3 頁 JavaThreads 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. Thread vs. Process

5 交通大學資訊工程學系 蔡文能 8- 第 4 頁 JavaThreads TestTea.java (1/3) //TestTea.java --- by ///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 TestTea.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 TeaOK.Java

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

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

8 交通大學資訊工程學系 蔡文能 8- 第 7 頁 JavaThreads 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. Multitasking and Multithreading

9 交通大學資訊工程學系 蔡文能 8- 第 8 頁 JavaThreads 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 ThreadSubclass class ThreadX extends Thread { public void run( ) { //logic for the thread }} ThreadX tx = new ThreadX( ); tx.start( ); How to create Java Thread (1/2)

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

11 交通大學資訊工程學系 蔡文能 8- 第 10 頁 JavaThreads 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 group, Runnable target) This creates a new Thread object in the specified Threadgroup.

12 交通大學資訊工程學系 蔡文能 8- 第 11 頁 JavaThreads Methods in Thread Class static methods: activeCount();currentThread();sleep();yield(); instance methods: getPriority( ); setPriority( ); start( ); stop( ); stop( ); (deprecated) run( ); isAlive( ); suspend( ); resume( ); join( );

13 交通大學資訊工程學系 蔡文能 8- 第 12 頁 JavaThreads 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 SimpleThread extends Thread { private int countDown = 3; private static int threadCount = 0; private int threadNumber = ++threadCount; public SimpleThread( ) { System.out.println("Making" + threadNumber++); }

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

15 交通大學資訊工程學系 蔡文能 8- 第 14 頁 JavaThreads One possible output of ‘ SimpleThread ’ : Making 1All Threads Started Making 2Thread 2(3) Making 3Thread 2(2) Making 4Thread 6(3) Making 5Thread 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) Creating Threads (3/4)

16 交通大學資訊工程學系 蔡文能 8- 第 15 頁 JavaThreads One possible output of ‘ SimpleThread ’ : T main T0T0T0T0 T1T1T1T1 T2T2T2T2 T3T3T3T3 T4T4T4T4 Making 1 Making 2 Making 3 Making 4 Making 5 3(3)3(2) 3(1)4(3)4(2) 4(1)6(3)6(2) 6(1)5(3)5(2) 5(1)2(3)2(2) 2(1) All Thread started Creating Threads (4/4)

17 交通大學資訊工程學系 蔡文能 8- 第 16 頁 JavaThreads Synchronization is a mechanism to control the 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 shouldobtain the semaphore associated with that region – if it is already taken, then the thread blocks (waits) until thesemaphore is released. Synchronization in Threads (1/5)

18 交通大學資訊工程學系 蔡文能 8- 第 17 頁 JavaThreads 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);} } Synchronization in Threads (2/5)

19 交通大學資訊工程學系 蔡文能 8- 第 18 頁 JavaThreads catch (Exception e) { e.printStackTrace(); } } /* run */ } /* Customer */ public class BankDemo { 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( ); } Synchronization in Threads (3/5)

20 交通大學資訊工程學系 蔡文能 8- 第 19 頁 JavaThreads //Wait for customer threads to complete for (int i = 0; i < NUMCUSTOMER; i++) { try { customer[i].join( ); } catch (InterruptedException e) { e.printStackTrace( ); } //Display account balance System.out.println(account.getBalance( ) ); } Synchronization in Threads (4/5)

21 交通大學資訊工程學系 蔡文能 8- 第 20 頁 JavaThreads 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 threadis 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 arewaiting for the producer are notified once the elements areproduced.

22 交通大學資訊工程學系 蔡文能 8- 第 21 頁 JavaThreads 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 InterruptedException - void wait(long msec, int nsec) throws InterruptedException -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. Thread Communication (1/6)

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

24 交通大學資訊工程學系 蔡文能 8- 第 23 頁 JavaThreads 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( ) ); } Thread Communication (3/6)

25 交通大學資訊工程學系 蔡文能 8- 第 24 頁 JavaThreads 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 (InterruptedException ie) { ie.printStackTrace( ); System.exit(0); }} /* add */ Thread Communication (4/6)

26 交通大學資訊工程學系 蔡文能 8- 第 25 頁 JavaThreads //Add data to array and adjust write pointer array[w++] = i; if (w >= SIZE) w = 0; //Increment count ++count; //Notify waiting threads notifyAll( ); } synchronized int remove( ) { //wait while the queue is empty while (count == 0) { try { wait( ); } catch (InterruptedException ie) { ie.printStackTrace( ); System.exit(0);}} Thread Communication (5/6)

27 交通大學資訊工程學系 蔡文能 8- 第 26 頁 JavaThreads 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 notifyAll( ); return element; }} public class ProducerConsumer { public static void main(String args[ ]) { Queue queue = new Queue( ); new Producer(queue).start( ); new Consumer( " ConsumerA", queue).start( ); new Consumer( " ConsumerB ", queue).start( ); new Consumer( " ConsumerC ", queue).start( );}}

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

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

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

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

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

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

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

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

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

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

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

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

40 交通大學資訊工程學系 蔡文能 8- 第 39 頁 JavaThreads 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

41 交通大學資訊工程學系 蔡文能 8- 第 40 頁 JavaThreads 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

42 交通大學資訊工程學系 蔡文能 8- 第 41 頁 JavaThreads 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.

43 交通大學資訊工程學系 蔡文能 8- 第 42 頁 JavaThreads Thread Priority The priority values range from 1 to 10, in increasing priority

44 交通大學資訊工程學系 蔡文能 8- 第 43 頁 JavaThreads 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 setPriority() method The priority of a thread may be obtained using getPriority() Priority constants are defined: MIN_PRIORITY=1 MAX_PRIORITY=10 NORM_PRIORITY=5

45 交通大學資訊工程學系 蔡文能 8- 第 44 頁 JavaThreads Socket Programming 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.

46 交通大學資訊工程學系 蔡文能 8- 第 45 頁 JavaThreads Sever - client communication A socket can be considered as a connection point. IP address port1 portN IP s …... IP c …... Port’1 Port’M IP address SEVER: CLIENT: Socket s (Ip c, Port’sM, port1) Socket c (Ip s, Port1, port’M)

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

48 交通大學資訊工程學系 蔡文能 8- 第 47 頁 JavaThreads import java.net.*; import java.io.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); //1 out = new PrintWriter(echoSocket.getOutputStream(), true); //2 in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException 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); }

49 交通大學資訊工程學系 蔡文能 8- 第 48 頁 JavaThreads BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { //3 out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); //4 in.close(); //4 stdIn.close(); echoSocket.close(); //5 }

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

51 交通大學資訊工程學系 蔡文能 8- 第 50 頁 JavaThreads Socket clientSocket = null; try { clientSocket = serverSocket.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.

52 交通大學資訊工程學系 蔡文能 8- 第 51 頁 JavaThreads PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; // initiate conversation with client KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if(outputLine.equals("Bye.")) break; }

53 交通大學資訊工程學系 蔡文能 8- 第 52 頁 JavaThreads 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). More reference: 聊天室程式範例 ChatServer.java

54 交通大學資訊工程學系 蔡文能 8- 第 53 頁 JavaThreads 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.

55 交通大學資訊工程學系 蔡文能 8- 第 54 頁 JavaThreads TCP/IP 網路通訊協定 de facto Standard ( 業界標準 ) TCP/IP network model Layer Function ApplicationEnd-user application programs Transport Communication among programs on a net (TCP/UDP) NetworkBasic 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.

56 交通大學資訊工程學系 蔡文能 8- 第 55 頁 JavaThreads TCP/IP 網路通訊協定 arprlogin, talk, ftp, DNSNFS, DNStraceroute TCPUDP IPICMP ARP, Device Drivers Ethernet Header IP Header TCP Header Application Data Ethernet Trailer ETHERNET FRAME Layer

57 交通大學資訊工程學系 蔡文能 8- 第 56 頁 JavaThreads 常見名詞術語 MAC Address00-D0-B7-25-3F-A8 IP Address Prot #TCP 21 (for FTP) FQDNftp.csie.nctu.edu.tw DNS ServerDomain Name Service Gateway 閘道口, LAN 與 WAN 交界口 Router, Switch, Hub  Layer 3 Switch ==~~ Router

58 交通大學資訊工程學系 蔡文能 8- 第 57 頁 JavaThreads

59 交通大學資訊工程學系 蔡文能 8- 第 58 頁 JavaThreads CSMA/CD 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.

60 交通大學資訊工程學系 蔡文能 8- 第 59 頁 JavaThreads

61 交通大學資訊工程學系 蔡文能 8- 第 60 頁 JavaThreads OSI 7-Layers Reference Model ISO: International Standard Organization OSI : Open System Interconnection  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)

62 交通大學資訊工程學系 蔡文能 8- 第 61 頁 JavaThreads 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.

63 交通大學資訊工程學系 蔡文能 8- 第 62 頁 JavaThreads Physical Layer ( 實體層 ) 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 實體層 : 定義網路媒介的型態、連接器的型態、以及通訊訊號的型態

64 交通大學資訊工程學系 蔡文能 8- 第 63 頁 JavaThreads 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)

65 交通大學資訊工程學系 蔡文能 8- 第 64 頁 JavaThreads Encapsulation ( 封裝 ) Lower layers add headers (and sometimes trailers) to data from higher layers Application Transport Network Data Link Network Data Transport Layer DataHeader Network Layer Data Header Data Header Link Layer Data Data Header Trailer

66 交通大學資訊工程學系 蔡文能 8- 第 65 頁 JavaThreads Encapsulation Details (Ethernet Frame types in hex, others in decimal)  dest addr source addr Ethernet frame type data CRC  Source addr Dest. addr data protocol type  IP header hdr cksum ARP RARP Novell IP Others AppleTalk  data TCP src port  header TCP dest port FTP server telnet server echo server discard server User process UDP 17 6 IGMP ICMP 1 2 TCP x0800 x8035 x0806

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

68 交通大學資訊工程學系 蔡文能 8- 第 67 頁 JavaThreads Internet Addressing : IP address IP address, 32 bits (IPV4) Network identifier (identifying the domain)  Assigned under the authority of ICANN  e.g for Addison Wesley Longman Host address  Assigned by local authority  e.g Domain Naming System (DNS)  e.g.  Top-level domain (TLD): e.g. com.tw, edu.tw, gov.ca, org, net

69 交通大學資訊工程學系 蔡文能 8- 第 68 頁 JavaThreads 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.

70 交通大學資訊工程學系 蔡文能 8- 第 69 頁 JavaThreads 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

71 交通大學資訊工程學系 蔡文能 8- 第 70 頁 JavaThreads 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.

72 交通大學資訊工程學系 蔡文能 8- 第 71 頁 JavaThreads 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.

73 交通大學資訊工程學系 蔡文能 8- 第 72 頁 JavaThreads TCP is Reliable 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

74 交通大學資訊工程學系 蔡文能 8- 第 73 頁 JavaThreads ClientServer SYN x, ACK 0 SYN y, ACK x+1 SYN x+1, ACK y+1 LISTENing SYN_RCVD ESTABLISHED backlog TCP -- connection-oriented 3-way Hand Shaking

75 交通大學資訊工程學系 蔡文能 8- 第 74 頁 JavaThreads TCP Segment Format Destination Port Options (if any) Data 1 byte Source Port Sequence Number Request Number (ACK Seqno) 1 byte offsetReser.ControlWindow ChecksumUrgent Pointer

76 交通大學資訊工程學系 蔡文能 8- 第 75 頁 JavaThreads UDP Datagram Format Datagram Delivery Connectionless Unreliable Source PortDestination Port LengthChecksum Data 8 bytes UDP Header

77 交通大學資訊工程學系 蔡文能 8- 第 76 頁 JavaThreads IP: Internet Protocol IP Header: 20 ~ 60 bytes  Frame type = 0x0800  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  /8, /12, /16 Related Commands:  ifconfig, netstat

78 交通大學資訊工程學系 蔡文能 8- 第 77 頁 JavaThreads IP Datagram VERSHL Fragment Offset Fragment LengthService Datagram IDFLAG TTL Protocol Header Checksum Source Address Destination Address Options (if any) Data 1 byte

79 交通大學資訊工程學系 蔡文能 8- 第 78 頁 JavaThreads Internet Address (IPv4 Addresses) Five Classes Class A0netidhostid Class B10netidhostid Class C110netidhostid Class D1110 Multicast Address Class E11110Reserved for Future Use IP Address Format Identifies a networkIdentifies a host on that network (netid, hostid ) Dotted Decimal Notation 代表任何一台 IP 主機自 己

80 交通大學資訊工程學系 蔡文能 8- 第 79 頁 JavaThreads CIDR -- Classless Inter Domain Routing 在 1993 年 IEEE Network 的提案增加了 CIDR 的擴充, 而打破了 Class 分級的局限。如果您的系統支持 CIDR 協定,就可以拋開等級的界限,使用可變長度的 netmask (VLSM) 靈活的的設計 IP 網路的範圍與路由。 當然,如果要和其它網路溝通,您使用的 Router 也必須 支援 CIDR 才行,不過,現在的 Router 鮮有不使用 CIDR 的了。 引入 CIDR 之後,如果您覺得 / 和 / 這樣的 IP 表現方法實在太麻 煩了,則可用一個更好的表示法﹕使用 mask 的 bit 數目長 度表示 Net Mask 。這樣我們就可以將前面兩個 IP 寫成 這樣﹕ /16 和 /24 。

81 交通大學資訊工程學系 蔡文能 8- 第 80 頁 JavaThreads 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

82 交通大學資訊工程學系 蔡文能 8- 第 81 頁 JavaThreads 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 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.

83 交通大學資訊工程學系 蔡文能 8- 第 82 頁 JavaThreads Programming in TCP 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.

84 交通大學資訊工程學系 蔡文能 8- 第 83 頁 JavaThreads Programming in UDP UDP  The datagram packet contains the port number of its destination.  UDP routes the packet to the appropriate application.

85 交通大學資訊工程學系 蔡文能 8- 第 84 頁 JavaThreads What Is a URL? URL (Uniform Resource Locator)  A reference (an address) to a resource on the Internet. E.g., #a1 ftp://ftp.csie.nctu.edu.tw/pub/CSIE/course/cs1/ Host NameThe name of the machine on which the resource lives. FilenameThe pathname to the file on the machine. Port NumberThe port number to which to connect (optional). ReferenceA reference to a named anchor within a resource that usually identifies a specific location within a file (optional).

86 交通大學資訊工程學系 蔡文能 8- 第 85 頁 JavaThreads Creating a URL Simplest way: URL gamelan = new URL("http://www.gamelan.com/"); Creating a URL Relative to Another URL gamelan = new URL("http://www.gamelan.com/pages/"); URL gamelanGames = new URL(gamelan, "Gamelan.game.html"); URL gamelanNetwork = 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:

87 交通大學資訊工程學系 蔡文能 8- 第 86 頁 JavaThreads Exceptions MalformedURLException  If the arguments to the constructor refer to a null or unknown protocol. try { URL myURL = new URL(...) } catch (MalformedURLException e) { //... // exception handler code here //... }

88 交通大學資訊工程學系 蔡文能 8- 第 87 頁 JavaThreads Parsing a URL getProtocol  Returns the protocol identifier component of the URL. getHost  Returns the host name component of the URL. getPort  Returns the port number component of the URL.  If the port is not set, getPort returns -1. getFile  Returns the filename component of the URL. getRef  Returns the reference component of the URL.

89 交通大學資訊工程學系 蔡文能 8- 第 88 頁 JavaThreads import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL("http://java.sun.com:80/docs/books/” + "tutorial/index.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); } Result: protocol = http host = java.sun.com filename = /docs/books/tutorial/index.html port = 80 ref = DOWNLOADING

90 交通大學資訊工程學系 蔡文能 8- 第 89 頁 JavaThreads Reading Directly from a URL Call the URL 's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream object. openStream() = = = openConnection().getInputStream()

91 交通大學資訊工程學系 蔡文能 8- 第 90 頁 JavaThreads 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/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }

92 交通大學資訊工程學系 蔡文能 8- 第 91 頁 JavaThreads Setting the Proxy Host (Java Application)  UNIX java -Dhttp.proxyHost=proxyhost [-Dhttp.proxyPort=portNumber] URLReader  DOS shell (Windows 95/NT) java -Dhttp.proxyHost=proxyhost [-Dhttp.proxyPort=portNumber] URLReader Setting the Proxy Host (Java Applet)  Follow the setting of your web browser.

93 交通大學資訊工程學系 蔡文能 8- 第 92 頁 JavaThreads Connecting to a URL Call the URL object's openConnection method to connect to it. URLConnection is an HTTP-centric class. try { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yahooConnection = yahoo.openConnection(); } catch (MalformedURLException e) { // new URL() failed //... } catch (IOException e) { // openConnection() failed... }

94 交通大學資訊工程學系 蔡文能 8- 第 93 頁 JavaThreads 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.

95 交通大學資訊工程學系 蔡文能 8- 第 94 頁 JavaThreads import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }

96 交通大學資訊工程學系 蔡文能 8- 第 95 頁 JavaThreads A Java program can interact with CGI scripts on the server side. 1.Create a URL. 2.Open a connection to the URL. 3.Set output capability on the URLConnection. 4.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.

97 交通大學資訊工程學系 蔡文能 8- 第 96 頁 JavaThreads 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 stringToReverse = URLEncoder.encode(args[0]); URL url = new URL("http://java.sun.com/cgi-bin/backwards"); //1 URLConnection connection = url.openConnection(); //2 connection.setDoOutput(true); //3 PrintWriter out = new PrintWriter( connection.getOutputStream() ); //4 out.println("string=" + stringToReverse); //5 out.close(); //6

98 交通大學資訊工程學系 蔡文能 8- 第 97 頁 JavaThreads BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream() )); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }

99 交通大學資訊工程學系 蔡文能 8- 第 98 頁 JavaThreads Threads and Networking in Java 謝謝捧場 蔡文能


Download ppt "交通大學資訊工程學系 Programming in Java Thread, Network programming 蔡文能 交通大學資訊工程學系"

Similar presentations


Ads by Google