交通大學資訊工程學系 programming in java thread, network programming 蔡文能...

98
交交交交交交交交交交 Programming in Java Thread, Network programming 蔡蔡蔡 蔡蔡蔡蔡蔡蔡蔡蔡蔡蔡 [email protected]

Post on 19-Dec-2015

314 views

Category:

Documents


3 download

TRANSCRIPT

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

交通大學資訊工程學系

Programming in Java

Thread,

Network programming

蔡文能交通大學資訊工程學系[email protected]

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

交通大學資訊工程學系 蔡文能 第 2頁

Java Threads

AgendaThreads and MultithreadingCreating a Thread extending the Thread class implementing the Runnable interface

Deadlock and Synchronization in ThreadsNetwork Programming TCP/IP protocols URL : read/write Socket programming

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

交通大學資訊工程學系 蔡文能 第 3頁

Java Threads

• 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 untilnow 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

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

交通大學資訊工程學系 蔡文能 第 4頁

Java Threads

TestTea.java (1/3)

//TestTea.java --- by [email protected]

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

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

交通大學資訊工程學系 蔡文能 第 5頁

Java Threads

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!"); }}

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

交通大學資訊工程學系 蔡文能 第 6頁

Java Threads

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}

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

交通大學資訊工程學系 蔡文能 第 7頁

Java Threads

• 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

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

交通大學資訊工程學系 蔡文能 第 8頁

Java Threads

• 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

ThreadThread

ThreadSubclassThreadSubclass

class ThreadX extends class ThreadX extends ThreadThread { {public void run( ) {public void run( ) {//logic for the thread//logic for the thread}}

}}

ThreadX tx = new ThreadX( );ThreadX tx = new ThreadX( );tx.start( );tx.start( );

How to create Java Thread (1/2)

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

交通大學資訊工程學系 蔡文能 第 9頁

Java Threads

RunnableRunnable

SomeSubclassSomeSubclass

class RunnableY class RunnableY implementsimplements RunnableRunnable { {public void public void runrun ( ) { ( ) {//logic for the thread//logic for the thread}}

}}

RunnableY ry = new RunnableY();RunnableY ry = new RunnableY();Thread ty = new Thread(ry);Thread ty = new Thread(ry);ty.start();ty.start();

implementsimplements

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

In both methods, the run( ) method should be implemented.

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

交通大學資訊工程學系 蔡文能 第 10頁

Java Threads

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

package.• Using an object of this class, the corresponding

thread canbe stopped, paused, and resumed.

• There are many constructors and methods for this class, wewill 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.

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

交通大學資訊工程學系 蔡文能 第 11頁

Java Threads

Methods in Thread Class

static methods:static methods:activeCount();activeCount();currentThread();currentThread();sleep();sleep();yield();yield();

instance methods:instance methods:getPriority( );getPriority( );setPriority( );setPriority( );start( );start( );

stop( ); stop( ); (deprecated)run( );run( );isAlive( );isAlive( );suspend( );suspend( );resume( );resume( );join( );join( );

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

交通大學資訊工程學系 蔡文能 第 12頁

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

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++);}

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

交通大學資訊工程學系 蔡文能 第 13頁

Java Threads

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)

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

交通大學資訊工程學系 蔡文能 第 14頁

Java Threads

• One possible output of ‘SimpleThread’:

Making 1 All Threads StartedMaking 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)

Creating Threads (3/4)

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

交通大學資訊工程學系 蔡文能 第 15頁

Java Threads

• One possible output of ‘SimpleThread’:

TTmainmain TT00 TT11 TT22 TT33 TT44

Making 1Making 1 Making 2Making 2 Making 3Making 3 Making 4Making 4 Making 5Making 5

3(3)3(3)

3(2)3(2)

3(1)3(1)

4(3)4(3)

4(2)4(2)

4(1)4(1)

6(3)6(3)

6(2)6(2)

6(1)6(1)

5(3)5(3)

5(2)5(2)

5(1)5(1)

2(3)2(3)

2(2)2(2)

2(1)2(1)

All Thread startedAll Thread started

Creating Threads (4/4)

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

交通大學資訊工程學系 蔡文能 第 16頁

Java Threads

• Synchronization is a mechanism to control the theexecution 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 toidentify a segment of code or method that

should beaccessible 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 the semaphore is released.

Synchronization in Threads (1/5)

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

交通大學資訊工程學系 蔡文能 第 17頁

Java Threads

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)

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

交通大學資訊工程學系 蔡文能 第 18頁

Java Threads

catch (Exception e) { e.printStackTrace();

} } /* run */} /* Customer */public class BankDemo {

private final static int NUMCUSTOMER = 10;public static void main(String args[ ]) {

//Create accountAccount account = new Account();//Create and start customer threadsCustomer customer[ ] = new

Customer[NUMCUSTOMER];for (int i = 0; i < NUMCUSTOMER; i++) {

customer[i] = new Customer(account);customer[i].start( );

}

Synchronization in Threads (3/5)

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

交通大學資訊工程學系 蔡文能 第 19頁

Java Threads

//Wait for customer threads to completefor (int i = 0; i < NUMCUSTOMER; i++) {

try {customer[i].join( );

}catch (InterruptedException e) {

e.printStackTrace( );}

}//Display account balanceSystem.out.println(account.getBalance( ) );

}}

Synchronization in Threads (4/5)

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

交通大學資訊工程學系 蔡文能 第 20頁

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.

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

交通大學資訊工程學系 蔡文能 第 21頁

Java Threads

• 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 methodcan 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)

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

交通大學資訊工程學系 蔡文能 第 22頁

Java Threads

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)

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

交通大學資訊工程學系 蔡文能 第 23頁

Java Threads

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)

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

交通大學資訊工程學系 蔡文能 第 24頁

Java Threads

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 fullwhile (count == SIZE) {

try {wait( );

}catch (InterruptedException ie) {

ie.printStackTrace( );System.exit(0);

}} /* add */

Thread Communication (4/6)

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

交通大學資訊工程學系 蔡文能 第 25頁

Java Threads

//Add data to array and adjust write pointerarray[w++] = i;if (w >= SIZE)

w = 0;//Increment count

++count;//Notify waiting threadsnotifyAll( );}synchronized int remove( ) {

//wait while the queue is emptywhile (count == 0) {

try { wait( ); }catch (InterruptedException ie) {

ie.printStackTrace( );System.exit(0);}}

Thread Communication (5/6)

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

交通大學資訊工程學系 蔡文能 第 26頁

Java Threads

Thread Communication (6/6)//read data from array and adjust read pointerint element = array[r++];if (r >= SIZE)

r = 0;//Decrement count

--count;//Notify waiting threadsnotifyAll( ); 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( );}}

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

交通大學資訊工程學系 蔡文能 第 27頁

Java Threads

Thread Lifecycle

Born

BlockedRunnable

Dead

stop( )

start( )

stop( )

Active

block on I/O

I/O complete

JVM

sleep(time)

wake up

suspend()

resume()

wait( )

notify( )return( )

return( )

yield( )

藍色的是deprecated

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

交通大學資訊工程學系 蔡文能 第 28頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 29頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 30頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 31頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 32頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 33頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 34頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 35頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 36頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 37頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 38頁

Java Threads

Wait/Notify Sequence

Lock Object

ConsumerThread

ProducerThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Reacquire lock8. Return from wait()

9. consumeResource();10. }

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

交通大學資訊工程學系 蔡文能 第 39頁

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

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

交通大學資訊工程學系 蔡文能 第 40頁

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

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

交通大學資訊工程學系 蔡文能 第 41頁

Java Threads

Deadlock

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

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

交通大學資訊工程學系 蔡文能 第 42頁

Java Threads

Thread Priority

The priority values range from 1 to 10, in increasing priority

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

交通大學資訊工程學系 蔡文能 第 43頁

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 setPriority() method

The priority of a thread may be obtained using getPriority()

Priority constants are defined: MIN_PRIORITY=1MAX_PRIORITY=10NORM_PRIORITY=5

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

交通大學資訊工程學系 蔡文能 第 44頁

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.

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

交通大學資訊工程學系 蔡文能 第 45頁

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 becomea de facto standard used by many vendors.

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

交通大學資訊工程學系 蔡文能 第 46頁

Java Threads

TCP/IP 網路通訊協定

arp rlogin, talk, ftp, DNS NFS, DNS traceroute

TCP UDP

IP ICMP

ARP, Device Drivers

EthernetHeader

IPHeader

TCPHeader

ApplicationData

EthernetTrailer

ETHERNET FRAME

4

3

2

1

Layer

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

交通大學資訊工程學系 蔡文能 第 47頁

Java Threads

常見名詞術語MAC Address 00-D0-B7-25-3F-A8

IP Address 140.113.2.138

Prot # TCP 21 (for FTP)

FQDN ftp.csie.nctu.edu.tw

DNS Server Domain Name Service

Gateway 閘道口 , LAN與WAN交界口Router, Switch, Hub Layer 3 Switch ==~~ Router

[email protected]

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

交通大學資訊工程學系 蔡文能 第 48頁

Java Threads

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

交通大學資訊工程學系 蔡文能 第 49頁

Java Threads

CSMA/CD Carrier Sense Multiple Access

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

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

交通大學資訊工程學系 蔡文能 第 50頁

Java Threads

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

交通大學資訊工程學系 蔡文能 第 51頁

Java Threads

OSI 7-Layer Reference Model

OSI

ISO

Proposed by International Organization for Standardization (ISO)

•It prevents changes in one layer from affecting the other layers, so that they can develop more quickly.

分層負責 ; 分工合作

上司管下司鋤頭管畚箕

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

交通大學資訊工程學系 蔡文能 第 52頁

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.

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

交通大學資訊工程學系 蔡文能 第 53頁

Java Threads

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 [email protected]

實體層 :定義網路媒介的型態、連接器的型態、以及通訊訊號的型態

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

交通大學資訊工程學系 蔡文能 第 54頁

Java Threads

Data Link Layer (資料連結層 )Layer 2 creates data frames to send to Layer 1On 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 integrityDetects errors and discards frames containing errorsPDU (Protocol Data Units )at Layer 2 is called a frameThe 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)

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

交通大學資訊工程學系 蔡文能 第 55頁

Java Threads

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

Application

Transport

Network

Data Link

Data Link

Network

Data

Transport Layer DataHeader

Network Layer DataHeader

DataHeaderHeader

Link Layer Data

DataHeaderHeader

Header

Header

Trailer

Trailer

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

交通大學資訊工程學系 蔡文能 第 56頁

Java Threads

Encapsulation Details

(Ethernet Frame types in hex, others in decimal)

destaddr

sourceaddrEthernet frame type data CRC

Sourceaddr

Dest.addr dataprotocol type

IP header

hdrcksumARP

RARPNovell

IP

Others

AppleTalk

dataTCP src port

headerTCP dest

port

FTPserver

telnetserver

echoserver

discardserver23

7

921User processUser processUser processUser process

1024-5000

UDP176

IGMP

ICMP 1

2

TCP

IPIP

TCPTCP

x0800

x8035x0806

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

交通大學資訊工程學系 蔡文能 第 57頁

Java Threads

Ethernet Frame Structure

Sending adapter encapsulates IP datagram (or other network layer protocol packet) in Ethernet frame :

Preamble: 7 bytes with pattern 10101010 followed by one byte with pattern 10101011 used to synchronize receiver, sender clock rates

PreambleDestination

AddressSource Address

Frame Type

Frame Data CRC

8 octets 6 octets 6 octets 2 octets 46-1500 octets 4 octets

( 0800 表示 IP datagram)

Octet 就是8-bit 的Byte

網路卡

先填對方的 MAC address

CRC : Cyclic Redundency Check

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

交通大學資訊工程學系 蔡文能 第 58頁

Java Threads

Internet Addressing : IP addressIP address, 32 bits (IPV4)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

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

交通大學資訊工程學系 蔡文能 第 59頁

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.comTop level domain = classification of domain owner

By usage – Example: .com = commercial By country – Example: .au = Australia

Subdomains and individual machine namesAssigned by domain ownerDomain owner must run a name server.

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

交通大學資訊工程學系 蔡文能 第 60頁

Java Threads

Name server (Domain Name Service)

Maintains a directory containing the mnemonic address and the corresponding numeric IP address within the domainResponds to requests regarding address informationAll of the name servers throughout the Internet constitute an Internet-wide directory systemWhen 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 formSuch a task is normally completed in a fraction of a second

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

交通大學資訊工程學系 蔡文能 第 61頁

Java Threads

TCP and UDPTCP (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.

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

交通大學資訊工程學系 蔡文能 第 62頁

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.

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

交通大學資訊工程學系 蔡文能 第 63頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 64頁

Java Threads

Client ServerSYNx , ACK0

SYNy , ACKx+1

SYNx+1 , ACKy+1

LISTENing

SYN_RCVD

ESTABLISHED

backlog

TCP -- connection-oriented3-way Hand Shaking

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

交通大學資訊工程學系 蔡文能 第 65頁

Java Threads

TCP Segment Format

Destination Port

Options (if any)

Data

1 byte 1 byte

Source Port

Sequence Number

Request Number (ACK Seqno)

1 byte 1 byte

offset Reser. Control Window

Checksum Urgent Pointer

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

交通大學資訊工程學系 蔡文能 第 66頁

Java Threads

UDP Datagram Format

Datagram Delivery

Connectionless

Unreliable

Source Port Destination Port

Length Checksum

Data

8 bytes UDP Header8 bytes UDP Header

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

交通大學資訊工程學系 蔡文能 第 67頁

Java Threads

IP: Internet ProtocolIP Header: 20 ~ 60 bytes Frame type = 0x0800 TOS, identification, flags, TTL, protocol, options, …

IP Routing routing table

Subnetting, CIDR, and netmaskIP Fragmentation identification and fragment offset flags field (“more fragment” , “don’t fragment”)

Private IP addresses 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16

Related Commands: ifconfig, netstat

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

交通大學資訊工程學系 蔡文能 第 68頁

Java Threads

IP Datagram

VERS HL

Fragment Offset

Fragment LengthService

Datagram ID FLAG

TTL Protocol Header Checksum

Source Address

Destination Address

Options (if any)

Data

1 byte1 byte 1 byte 1 byte

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

交通大學資訊工程學系 蔡文能 第 69頁

Java Threads

Internet Address (IPv4 Addresses)Five Classes

0 1 2 3 4 8 16 24 31

Class A 0 netid hostid

Class B 1 0 netid hostid

Class C 1 1 0 netid hostid

Class D 1 1 1 0 Multicast Address

Class E 1 1 1 1 0 Reserved for Future Use

IP Address Format

Identifies a network Identifies a host on that network

(netid, hostid )

Dotted Decimal Notation 128.12.5.30 10000000 00001100 00000101 00011110

127.0.0.1 代表任何一台 IP 主機自己

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

交通大學資訊工程學系 蔡文能 第 70頁

Java Threads

CIDR -- Classless Inter Domain Routing• 在 1993 年 IEEE Network 的提案增加了 CIDR 的擴充,

而打破了 Class 分級的局限。如果您的系統支持 CIDR 協 定,就可以拋開等級的界限,使用可變長度的 netmask

(VLSM) 靈活的的設計 IP 網路的範圍與路由。當然,如果 要和其它網路溝通,您使用的 Router 也必須支援 CIDR

才行,不過,現在的 Router 鮮有不使用 CIDR 的了。• 引入 CIDR 之後,如果您覺得 169.158.88.254/255.255.0.0 和 140.113.1.1/255.255.255.0 這樣的 IP 表現方法實在太麻

煩了,則可用一個更好的表示法﹕使用 mask 的 bit 數目 長度表示 Net Mask 。這樣我們就可以將前面兩個 IP 寫成

這樣﹕ 169.158.88.254/16 和 140.113.1.1/24 。

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

交通大學資訊工程學系 蔡文能 第 71頁

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

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

交通大學資訊工程學系 蔡文能 第 72頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 73頁

Java Threads

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.

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

交通大學資訊工程學系 蔡文能 第 74頁

Java Threads

Programming in UDPUDP The datagram packet contains the port number of its destination. UDP routes the packet to the appropriate application.

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

交通大學資訊工程學系 蔡文能 第 75頁

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#a1

ftp://ftp.csie.nctu.edu.tw/pub/CSIE/course/cs1/

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

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

交通大學資訊工程學系 蔡文能 第 76頁

Java Threads

Creating a URL

Simplest way:URL gamelan = new URL("http://www.gamelan.com/");

Creating a URL Relative to Anotherhttp://www.gamelan.com/pages/Gamelan.game.htmlhttp://www.gamelan.com/pages/Gamelan.net.htmlURL 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 Constructorsnew 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

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

交通大學資訊工程學系 蔡文能 第 77頁

Java Threads

ExceptionsMalformedURLException 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

//. . .

}

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

交通大學資訊工程學系 蔡文能 第 78頁

Java Threads

Parsing a URLgetProtocol 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.

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

交通大學資訊工程學系 蔡文能 第 79頁

Java Threads

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 = httphost = java.sun.comfilename = /docs/books/tutorial/index.htmlport = 80ref = DOWNLOADING

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

交通大學資訊工程學系 蔡文能 第 80頁

Java Threads

Reading Directly from a URLCall 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()

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

交通大學資訊工程學系 蔡文能 第 81頁

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/");

BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }}

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

交通大學資訊工程學系 蔡文能 第 82頁

Java Threads

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.

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

交通大學資訊工程學系 蔡文能 第 83頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 84頁

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 serverReceiveing the data, processes it.

Then sends you a response, usually in the form of a new HTML page.

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

交通大學資訊工程學系 蔡文能 第 85頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 86頁

Java Threads

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.

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

交通大學資訊工程學系 蔡文能 第 87頁

Java Threads

import java.net.*;import java.io.*;

public class Reverse { public static void main(String[] args) throwsException { 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

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

交通大學資訊工程學系 蔡文能 第 88頁

Java Threads

BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }}

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

交通大學資訊工程學系 蔡文能 第 89頁

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.

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

交通大學資訊工程學系 蔡文能 第 90頁

Java Threads

Sever - client communicationSever - client communication

• A socket can be considered as a connection point.

IP addressIP address

port1port1 portportNN

IPIPss

… … ......

IPIPcc

… … ... ...

Port’1Port’1 Port’Port’MM

IP addressIP address

SEVER:SEVER:

CLIENT:CLIENT:

SocketSocketss(Ip(Ipcc, Port’s, Port’sMM, port1), port1)

SocketSocketcc(Ip(Ipss, Port1, port’, Port1, port’MM))

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

交通大學資訊工程學系 蔡文能 第 91頁

Java Threads

Reading from and Writing to a Socket

The client in a client-server architecture1. 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.

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

交通大學資訊工程學系 蔡文能 第 92頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 93頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 94頁

Java Threads

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

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

交通大學資訊工程學系 蔡文能 第 95頁

Java Threads

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.

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

交通大學資訊工程學系 蔡文能 第 96頁

Java Threads

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));String inputLine, outputLine;

// initiate conversation with clientKnockKnockProtocol 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;}

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

交通大學資訊工程學系 蔡文能 第 97頁

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

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

交通大學資訊工程學系 蔡文能 第 98頁

Java Threads

Threads and Networking in Java

謝謝捧場http://www.csie.nctu.edu.tw/~tsaiwn/oop/

蔡文能