Download Thread

Document related concepts
no text concepts found
Transcript
Programming in Java
Thread,
Network programming
蔡文能
交通大學資訊工程學系
[email protected]
交通大學資訊工程學系
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 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
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
交通大學資訊工程學系 蔡文能
第4頁
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!");
}
}
交通大學資訊工程學系 蔡文能
第5頁
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
}
交通大學資訊工程學系 蔡文能
第6頁
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 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( );
交通大學資訊工程學系 蔡文能
第8頁
Java
Threads
How to create Java Thread (2/2)
- implementing the Runnable interface for an object
Runnable
implements
SomeSubclass
class RunnableY implements Runnable {
public void run ( ) {
//logic for the thread
}
}
RunnableY ry = new RunnableY();
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 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.
交通大學資訊工程學系 蔡文能
第10頁
Java
Threads
Methods in Thread Class
static methods:
activeCount();
currentThread();
sleep();
yield();
交通大學資訊工程學系 蔡文能
instance methods:
getPriority( );
setPriority( );
start( );
stop( ); (deprecated)
run( );
isAlive( );
suspend( );
resume( );
join( );
第11頁
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 SimpleThread extends Thread {
private int countDown = 3;
private static int threadCount = 0;
private int threadNumber = ++threadCount;
public SimpleThread( ) {
System.out.println("Making" + threadNumber++);
}
交通大學資訊工程學系 蔡文能
第12頁
Java
Threads
Creating Threads (2/4)
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");
}
}
交通大學資訊工程學系 蔡文能
第13頁
Java
Threads
Creating Threads (3/4)
• One possible output of ‘SimpleThread’:
Making 1
Making 2
Making 3
Making 4
Making 5
Thread 3(3)
Thread 4(3)
Thread 4(2)
Thread 4(1)
Thread 5(3)
Thread 5(2)
Thread 5(1)
交通大學資訊工程學系 蔡文能
All Threads Started
Thread 2(3)
Thread 2(2)
Thread 6(3)
Thread 3(2)
Thread 2(1)
Thread 6(2)
Thread 6(1)
Thread 3(1)
第14頁
Java
Threads
Creating Threads (4/4)
• One possible output of ‘SimpleThread’:
Tmain
All Thread started
T0
T1
Making 1
Making 2
T2
T3
T4
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 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;
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.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( );
}
交通大學資訊工程學系 蔡文能
第18頁
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 (InterruptedException e) {
e.printStackTrace( );
}
}
//Display account balance
System.out.println(account.getBalance( ) );
}
}
交通大學資訊工程學系 蔡文能
第19頁
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 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.
交通大學資訊工程學系 蔡文能
第21頁
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;
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 = 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 */
交通大學資訊工程學系 蔡文能
第24頁
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
notifyAll( );
}
synchronized int remove( ) {
//wait while the queue is empty
while (count == 0) {
try { wait( ); }
catch (InterruptedException ie) {
ie.printStackTrace( );
System.exit(0);}}
交通大學資訊工程學系 蔡文能
第25頁
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
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( );}}
交通大學資訊工程學系 蔡文能
第26頁
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
I/O complete
第27頁
Java
Threads
Wait/Notify Sequence
1. synchronized(lock){
2.
lock.wait();
9.
consumeResource();
10. }
Lock Object
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
4. synchronized(lock)
5.
lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
Consumer
Thread
交通大學資訊工程學系 蔡文能
Producer
Thread
第34頁
Java
Threads
Wait/Notify Sequence
Lock Object
1. synchronized(lock){
2.
lock.wait();
9.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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.
consumeResource();
10. }
3. produceResource()
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 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, 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
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
priority
交通大學資訊工程學系 蔡文能
第42頁
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=1
MAX_PRIORITY=10
NORM_PRIORITY=5
交通大學資訊工程學系 蔡文能
第43頁
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
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, 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, Switch, Hub
 Layer 3 Switch
00-D0-B7-25-3F-A8
140.113.2.138
TCP 21 (for FTP)
ftp.csie.nctu.edu.tw
Domain Name Service
閘道口, LAN與WAN交界口
==~~
Router
[email protected]
交通大學資訊工程學系 蔡文能
第47頁
Java
交通大學資訊工程學系 蔡文能
Threads
第48頁
Java
Threads
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.
交通大學資訊工程學系 蔡文能
第49頁
Java
交通大學資訊工程學系 蔡文能
Threads
第50頁
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.
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 (實體層)

實體層 :定義網路媒介的型態、連接器的型態、以及通訊訊號的型態
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]
交通大學資訊工程學系 蔡文能
第53頁
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 higher layers
Data
Application
Transport
Header
Network Layer Data
Data
Header Header
Network
Network
Data Link
Data Link
Transport Layer Data
Header
Header
Link Layer Data
Header Header Header
交通大學資訊工程學系 蔡文能
Data
Trailer
Trailer
第55頁
Java
Threads
Encapsulation Details
1024-5000
FTP
server 21
User process
User process
User process
User process
telnet
23 server
7
echo
server




TCP src port TCP dest port header
ICMP
UDP 17
1
IGMP
2
IP header protocol type
x0806
Others

RARP x8035
Novell
AppleTalk
source
addr
IP x0800
Ethernet frame type
data
TCP
6

ARP
dest
addr
TCP
discard
9 server
Source Dest.
hdr
cksum addr
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 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
6 octets
2 octets
46-1500 octets
4 octets
先填對方的 MAC address
( 0800 表示 IP datagram)
Preamble:
7 bytes with pattern 10101010 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
IP 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
交通大學資訊工程學系 蔡文能
第58頁
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 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
 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 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
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 , ACK0
SYNy , ACKx+1
LISTENing
SYN_RCVD
backlog
SYNx+1 , ACKy+1
ESTABLISHED
交通大學資訊工程學系 蔡文能
第64頁
Java
Threads
TCP Segment Format
1 byte
1 byte
1 byte
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 UDP Header
Datagram Delivery
Connectionless
Unreliable
交通大學資訊工程學系 蔡文能
第66頁
Java
Threads
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
 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
Related Commands:
 ifconfig, netstat
交通大學資訊工程學系 蔡文能
第67頁
Java
Threads
IP Datagram
1 byte
1 byte
1 byte
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 (IPv4 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
1
1
4
8
16
netid
24
31
hostid
netid
hostid
netid
hostid
Multicast Address
0
Reserved for Future Use
IP Address Format
(netid, hostid )
Identifies a network
Identifies a host on that network
10000000 00001100 00000101 00011110
Dotted Decimal Notation
交通大學資訊工程學系 蔡文能
128.12.5.30
127.0.0.1 代表任何一台 IP 主機自
第69頁
己
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 。
交通大學資訊工程學系 蔡文能
第70頁
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.
 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
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
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 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).
交通大學資訊工程學系 蔡文能
第75頁
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 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:
http://www.gamelan.com:80/pages/Gamelan.network.html
交通大學資訊工程學系 蔡文能
第76頁
Java
Threads
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
//. . .
}
交通大學資訊工程學系 蔡文能
第77頁
Java
Threads
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.
交通大學資訊工程學系 蔡文能
第78頁
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 = 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 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()
交通大學資訊工程學系 蔡文能
第80頁
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();
}
}
交通大學資訊工程學系 蔡文能
第81頁
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.
交通大學資訊工程學系 蔡文能
第82頁
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
. . .
}
交通大學資訊工程學系 蔡文能
第83頁
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 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();
}
}
交通大學資訊工程學系 蔡文能
第85頁
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 {
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");
URLConnection connection = url.openConnection(); //2
connection.setDoOutput(true); //3
PrintWriter out =
new PrintWriter(connection.getOutputStream());
out.println("string=" + stringToReverse); //5
out.close(); //6
交通大學資訊工程學系 蔡文能
//1
//4
第87頁
Java
Threads
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine); in.close();
}
}
交通大學資訊工程學系 蔡文能
第88頁
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 connection point.
port1
SEVER:
portN
… ...
IP address
Sockets(Ipc, Port’sM, port1)
IP
s
IP address
Socketc(Ips, Port1, port’M)
CLIENT:
Port’1
交通大學資訊工程學系 蔡文能
Port’M
第90頁
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 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);
}
交通大學資訊工程學系 蔡文能
第92頁
Java
Threads
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
//4
in.close();
//4
stdIn.close();
echoSocket.close();
//3
//5
}
}
交通大學資訊工程學系 蔡文能
第93頁
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);
}
交通大學資訊工程學系 蔡文能
第94頁
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.
交通大學資訊工程學系 蔡文能
第95頁
Java
Threads
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;
}
交通大學資訊工程學系 蔡文能
第96頁
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
Threads and Networking in Java
謝謝捧場
http://www.csie.nctu.edu.tw/~tsaiwn/oop/
蔡文能
交通大學資訊工程學系 蔡文能
第98頁