Java系列概論 Java System Concepts

Download Report

Transcript Java系列概論 Java System Concepts

Java系列概論
網路入門程式
Java System Concepts and Network Programming
賈蓉生 胡大源 林金池 編著
第一章
導讀(Introduction)
1-1 簡介
1-2 本書主要內容
1-3 本書編著特色
1-4 光碟使用
1-1 簡介
• 本書是這一系列叢書的第二冊,以初學入門觀點
撰寫,內容從Java基礎程式到網路程式,期使一
位完全沒有接觸過Java的讀者,從陌生到熟練網
路程式。
1-2 本書主要內容
•
•
•
•
第一篇 Java基礎概念(Basic Concepts)
第二篇 網路串流(Data Stream in Network)
第三篇 網路群播(Multi Broadcast)
第四篇 圖型介面(GUI)與網路應用
1-3 本書編著特色
• (1) 輕鬆入門:本書以Java初學入門觀點切入網路程
式設計,配合範例輕鬆解說每一指令與原始類別之
用法、輕鬆入門。
• (2) 熟練實作:任何學習重點都搭配範例探討並實作
,完全剖析Java網路程式。
• (3) 問題導向:協助讀者提出問題,解決問題,本書
編輯問題339則(其中165則範例、174則習題)。
• (4) 原文接軌:編輯中英文索引751個(如附錄E、F),
已涵蓋所有Java有關網路程式之中英文專有名詞,
足夠讓讀者儲備未來閱讀原文書籍或期刊的能力。
1-4 光碟使用
• 本書隨書附光碟一片,內容有Java安裝程式(System)、範例應用程式
(Program);另於出版書局附教學光碟一片,內容有教學投影(Ppt)、習
題解答(Ex)、Java安裝程式(System)、範例應用程式(Program)。
•
• 1、Java安裝程式(System):置於光碟目錄System內,下載自昇陽(SUN)
最新6.0 Java安裝程式,讀者可依附錄A內容安裝Java。
•
• 2、範例應用程式(Program):置於光碟目錄Program內,配合各章節範
例執行賓作。
•
• 3、教學投影片(Ppt):置於教學光碟目錄Ppt內,以Power Point 依本書
各章節內容製作,用於堂課投影教學。
•
• 4、習題解答(Ex):置於教學光碟目錄Ex內,列出本書各章習題之解答
。
第一篇
Java基礎概念(Basic Concepts)
第二章
物件概念(Object Concepts)
2-1 簡介
2-2類別程序
2-3 新物件之產生
2-4 新物件之使用
2-5 區塊(Block)
2-6生存變數(Instance Variable)
2-7 類別變數(Class Variables)
2-8 習題(Exercises)
2-1 簡介
•
• Java是物件導向電腦程式語言(Object Oriented
Language),在Java環境中,一個類別程序(Class
Procedure) 就是一個物件。
2-2類別程序
• 一組具有某功能的程式碼是謂 “類別程序(Class
Procedure)”。
• 特徵有:(1) 以 “class” 作前置提示;(2) 有類別名
稱,本例是Mynumber;(3) 有功能意義,本例可
於變數number儲存一個整數;(4) 使用大括號 “{ }”
作為區塊範圍。
2-3 新物件之產生
• 內建資料型態(Built Data Types)
• 建構資料型態(Constructed Data Types)
2-4 新物件之使用
• 一旦新物件順利產生,即可依其特性參與程式執
行
範例1:設有檔案Ex02_4.java,其功能為解釋主體類別程序之地位
、與主導複製及使用檔案內其他類別程序產生的新物件。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int number;
03 }
04 class Ex02_4 {
05 public static void main(String[] args) {
06
Mynumber a= new Mynumber();
07
a.number= 10;
08
System.out.println("a.number= "+a.number);
09 }
10 }
2-5 區塊(Block)
• Java程式是以區塊(Block) 為組織基礎單位,每一
區塊單位以大括號涵蓋其範圍,各區塊彼此形成
上下隸屬、左右同儕的關係。
• 外部區塊為上司,內部區塊為下屬,平輩而互不
隸屬的區塊是為同儕。
範例2:設有檔案Ex02_5_1.java,其功能為解釋系統為了節省時間
與空間,每一區塊並非隨時都存在的,只有當被執行時才存在。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_5_1 {
02 public static void main(String[] args) {
03
04
05
{ int a = 3;
System.out.println("Block A and a = " + a);
}
06
07
08
{ int b = 5;
System.out.println("Block B and b = " + b);
}
09 }
10}
範例3:設有檔案Ex02_5_2.java,其功能為解釋兩個互不相關的區
塊,可宣告相同名稱之變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_5_2 {
02 public static void main(String[] args) {
03
04
05
{ int a = 3;
System.out.println("Block A and a = " + a);
}
06
07
08
{ int a = 5;
System.out.println("Block B and a = " + a);
}
09 }
10 }
範例4:設有檔案Ex02_5_3.java,其功能為解釋外部區塊與
內部區塊不得有相同名稱之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_5_3 {
02 public static void main(String[] args) {
03
04
05
06
07
08 }
09 }
{ int a = 3;
{ int a = 5;
System.out.println("a = " + a);
}
}
範例5:設有檔案Ex02_5_4.java,其功能為解釋內
部區塊可使用外部區塊之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_5_4 {
02 public static void main(String[] args) {
03
04
05
06
07
08
09 }
10 }
{ int a = 3;
{ int b = 5;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
範例6:設有檔案Ex02_5_5.java,其功能為解釋外
部區塊不得使用內部區塊之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_5_5 {
02 public static void main(String[] args) {
03
04
05
06
07
08
09 }
10}
{ int a = 3;
{ int b = 5;
}
System.out.println("a = " + a);
System.out.println("b = " + b);
}
2-6生存變數(Instance Variable)
• 變數是源自類別程序,如果未建立成新物件,雖
然已作變數宣告,變數仍因其所屬的物件不存在
而無法使用,這點與其他程式語言有所不同。
範例7:設有檔案Ex02_6_1.java,其功能為解釋在
類別程序內宣告之變數,無法直接使用。
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03 }
04 class Ex02_6_1 {
05 public static void main(String[] args) {
06
n = 10;
07
System.out.println("n = "+ n);
08 }
09 }
範例8:設有檔案Ex02_6_2.java,其功能為解
釋非生存區塊宣告之變數,無法直接使用。
•
•
•
•
•
•
•
•
•
01 class Ex02_6_2 {
02 int a;
03 public static void main(String[] args) {
04
a = 5;
05
System.out.println("a = "+ a);
06 }
07 }
2-7 類別變數(Class Variables)
• 凡於宣告時前置static的變數,是謂 “類別變數
(Class Variables)”,不需經過產生新物件的過程,
即可直接被使用。
範例9:設有檔案Ex02_7_1.java,其功能為解釋類
別變數之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 static int n;
03 }
04 class Ex02_7_1 {
05 public static void main(String[] args) {
06
Mynumber.n = 10;
07
System.out.println("n = "+ Mynumber.n);
08 }
09 }
範例10:設有檔案Ex02_7_2.java,其功能為解釋變數在自身類別
程序內宣告時,可標示所屬類別物件之名稱、或直接被使用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex02_7_2 {
02 static int a;
03
04
05
public static void main(String[] args) {
Ex02_7_2.a = 5;
System.out.println("Ex02_7_2.a = "+ Ex02_7_2.a);
06
a = 10;
07
System.out.println("a = "+ a);
08 }
09 }
第三章
運算式(Expression)與流程控制(Control Flow)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
3-1 簡介
3-2 變數
3-3運算關係式(Expression)
3-4 資料轉型(Type Conversion)
3-5 流程控制(Control Flow)
3-5-1 決策流程控制(Decision Control Flow)
3-5-1-1 if…else決策
3-5-1-2 else if決策
3-5-1-3 switch…case決策
3-5-2廻圈流程控制(Loop Control Flow)
3-5-2-1 while廻圈
3-5-2-2 do…while廻圈
3-5-2-3 for廻圈
3-6 break與continue
3-7 習題(Exercises)
3-1 簡介
•
• 於Java程式中,所有被使用的記憶體
(Memory) 都需作資料型態(Data Types) 之宣
告(Declare),以限制該記憶體儲存資料的型
態。
3-2 變數
• 內建資料型態(Built Data Types)
• 建構資料型態(Constructed Data Types)
範例11:設有檔案Ex03_2.java,其功能為解釋內建
資料型態、與建構資料型態之用法。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex03_2 {
05 public static void main(String[] args) {
06
int j;
07
Mynumber a;
08
09
10
j=3;
a = new Mynumber();
a.i = 5;
11
12
13
}
14 }
System.out.println("j = "+j);
System.out.println("a.i = "+a.i);
3-3運算關係式(Expression)
• 設有元素值a與b,若兩者之間存在某種關係元R,
即可以關係式 “aRb” 表示之。我們熟悉的關係元
如:“等於(=)”、“大於(>)”、“因此(→)”、“加(+)”、“
乘(×)” 等均屬之。
3-4 資料轉型(Type Conversion)
• 將一個變數(Variable) 的資料型態(Data Type) 轉換
成另一個資料型態,是謂 “資料轉型(Type
Conversion)”,例如將byte型態之變數轉換成int型
態來使用。
範例13: 設有檔案Ex03_4_1.java,其功能為解釋資料變數自動轉型之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_4_1 {
02 public static void main (String[] argv) {
03
byte bt;
04
short sh;
05
int in;
06
long lg;
07
float ft;
08
double db;
09
bt = 97;
10
sh = bt;
11
System.out.println("short<--byte:"+sh+"<--"+bt);
12
in = sh;
13
System.out.println("int<--short:"+in+"<--"+sh);
14
lg = in;
15
System.out.println("long<--int:"+lg+"<--"+in);
16
ft = lg;
17
System.out.println("float<--long:"+ft+"<--"+lg);
18
db = ft;
19
System.out.println("double<--float:"+db+"<--"+ft);
20 }
21 }
範例14: 設有檔案Ex03_4_2.java,其功能為解釋資料變數強迫轉型之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_4_2 {
02 public static void main (String[] argv) {
03
byte bt;
04
short sh;
05
int in;
06
long lg;
07
float ft;
08
double db;
09
db = 97.0;
10
ft = (float)db;
11
System.out.println("float<--double:"+ft+"<--"+db);
12
lg = (long)ft;
13
System.out.println("long<--float:"+lg+"<--"+ft);
14
in = (int)lg;
15
System.out.println("int<--long:"+in+"<--"+lg);
16
sh = (short)in;
17
System.out.println("short<--int:"+sh+"<--"+in);
18
bt = (byte)sh;
19
System.out.println("bt<--short:"+bt+"<--"+sh);
20 }
20 }
3-5 流程控制(Control Flow)
•
• 於Java程式中,常用之流程控制為 “決策流
程控制(Decision Control Flow)” 與 “廻圈流程
控制(Loop Control Flow)”。前者使用if…else
、else if、switch…case敘述式(Statements);
後者使用while、do…while、for廻圈。
範例15: 設有int變數a = 10,試求下列片斷程式之
執行結果。
•
• if ( a > 0)
•
System.out.println("執行真值敘述式: " + a);
• else {
•
a = 20;
•
System.out.println(“執行偽值敘述式: ” + a);
• }
範例16:設有檔案Ex03_5_1_2.java,其功能為解
釋else if區塊鏈、與多重多層決策之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_5_1_2 {
02 public static void main (String[] argv) {
03 int a = 3;
04 if (a == 1)
05
System.out.println("a is 1");
06
else if (a == 2)
07
System.out.println("a is 2");
08
else if (a == 3)
09
System.out.println("a is 3");
10
else
11
System.out.println("a is others");
12 }
13 }
範例17:設有檔案Ex03_5_1_3.java,其功能為解
釋switch…case區塊鏈多重多層決策之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_5_1_3 {
02 public static void main (String[] argv) {
03 int a = 3;
04 switch (a) {
05
case 1:
06
System.out.println("a is 1");
07
break;
08
case 2:
09
System.out.println("a is 2");
10
break;
11
case 3:
12
System.out.println("a is 3");
13
break;
14
default:
15
System.out.println("a is others");
16 }
17 }
18 }
範例18:設有檔案Ex03_5_2_1.java,其功能
為解釋while廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_5_2_1 {
02 public static void main (String[] argv) {
03 int a = 1;
04
05
06
07
08 }
09 }
while (a <= 3) {
System.out.println("a = : " + a);
a++;
}
範例19:設有檔案Ex03_5_2_2.java,其功能為解釋
do…while廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_5_2_2 {
02 public static void main (String[] argv) {
03 int a = 1;
04
05
06
07
08 }
09 }
do {
System.out.println("a = : " + a);
a++;
} while (a <= 3);
範例20:設有檔案Ex03_5_2_3.java,其功能為解
釋for廻圈之應用。
•
•
•
•
•
•
•
•
•
01 class Ex03_5_2_3 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=3; a++)
05
System.out.println("a = : " + a);
06 }
07 }
3-6 break與continue
•
• 在Java程式廻圈中,break用於跳出廻圈區塊,並
且不再執行該次廻圈內之重複執行式(Iteration
Expression);continue用於跳出該次廻圈,但並未
跳出區塊,仍繼續執行該次廻圈內之重複執行式
。
範例21:設有檔案Ex03_6_1.java,其功能為解釋
break在廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_6_1 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=5; a++) {
05
if(a==3)
06
break;
07
System.out.println("a = : " + a);
08 }
09 }
10 }
範例22:設有檔案Ex03_6_2.java,其功能為解釋
continue在廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_6_2 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=5; a++) {
05
if(a==3)
06
continue;
07
System.out.println("a = : " + a);
08 }
09 }
10 }
範例23:設有檔案Ex03_6_3.java,其功能為解釋break與廻
圈標籤之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_6_3 {
02 public static void main (String[] argv) {
03
int a, b;
04 L1: for(a=1; a<=2; a++) {
05
System.out.println("a = : " + a);
06 L2: for(b=1; b<=5; b++) {
07
if(b==3)
08
break L2;
09
System.out.println("b = : " + b);
10
}
11
}
12 }
13 }
範例24:設有檔案Ex03_6_4.java,其功能為解釋continue
與廻圈標籤之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex03_6_4 {
02 public static void main (String[] argv) {
03
int a, b;
04 L1: for(a=1; a<=2; a++) {
05
System.out.println("a = : " + a);
06 L2: for(b=1; b<=5; b++) {
07
if(b==3)
08
continue L2;
09
System.out.println("b = : " + b);
10
}
11
}
12 }
13 }
第四章
方法程序(Methods)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
4-1 簡介
4-2方法程序(Methods)
4-3 生存方法程序(Instance Methods)
4-4 類別方法程序(Class Methods)
4-5建構子(Constructor)
4-6方法程序重載(Method Overload)
4-7 public / private限制修飾子(Modifications)
4-8 this代名詞
4-8-1 類別代名詞
4-8-2 建構子代名詞
4-9 巢狀類別(Nested Class)
4-9-1 成員類別(Member Class)
4-9-2 區域類別(Local Class)
4-10 習題(Exercises)
4-1 簡介
•
• Java語言的方法程序(Methods),猶如其他
高階語言程式中的副程式(Subroutines)或函
數(Functions),是具有解決問題功能的程式
區塊
4-2方法程序(Methods)
• 為了方便,將常用的功能需求,先設計出一些內
建副程式(Subroutine) / 函數(Function),或Java之
方法程序(Methods),儲置於系統程式庫內,於爾
後設計程式時,視需要,由主程式呼叫有關的副
程式/函數、或方法程序,組成一個功能強大的工
作群。
範例25:設有檔案Ex04_2.java,其功能為解釋主體類別程序如何
呼叫使用方向程序?
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Study {
02 int credit=0;
03 void addcredit(int i) { credit += i; }
04 int totalcredit() { return credit; }
05 }
06 class Ex04_2 {
07 public static void main(String[] args) {
08
Study joe = new Study();
09
Study george = new Study );
10
joe.addcredit(12);
11
george.addcredit(9);
12
joe.addcredit(6);
13
george.addcredit(3);
14
System.out.println("joe studied: "+joe.totalcredit()+"credites");
15
System.out.println("george studied:
"+george.totalcredit()+"credites");
• 16 }
• 17 }
4-3 生存方法程序(Instance Methods)
• 方法程序也是一樣,有其所屬之類別物件,當所
屬類別物件生存時,該方法程序才可被執行使用
,如此隨所屬類別物件生存而生存之方法程序是
謂 “生存方法程序(Instance Methods)”。
範例26:設有檔案Ex04_3.java,其功能為解釋生存方法程序
(Instance Methods) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
class Number {
int n = 0;
void addN(int i) { n = i; }
int getN() { return n; }
}
class Ex04_3 {
public static void main(String[] args) {
Number N = new Number();
N.addN(10);
System.out.println(“使用方法程序 N.getN: ”+ N.getN());
N.n = 20;
System.out.println("使用變數 N.n: "+ N.n);
}
}
4-4 類別方法程序(Class Methods)
• 於變數宣告時,增列前置關鍵字 “static” 即可將該
變數一直保持在生存狀態,並等待被執行。
範例27:設有檔案Ex04_4.java,其功能為解釋類別方法程
序與變數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Number {
02 static int n = 0;
03 static void addN(int i) { n = i; }
04 static int getN() { return n; }
05 }
06 class Ex04_4 {
07 public static void main(String[] args) {
08
Number.addN(10);
09
System.out.println("Number.getN: " + Number.getN());
10
Number.n = 20;
11
System.out.println("Number.n: " + Number.n);
12 }
13 }
4-5建構子(Constructor)
•
• 一個類別程序含有多個不同功能的方法程序,其
中一個是具有代表性的方法程序,是謂該類別的 “
建構子(Constructor)”。
範例28:設有檔案Ex04_5_1.java,其功能為解釋建構子之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03
04
05
06
Mynumber() {
n = 3;
System.out.println("Here is Constructor and n = " + n);
}
07 int getnumber() { return n; }
08 }
09 class Ex04_5_1 {
10 public static void main(String[] args) {
11
Mynumber a = new Mynumber();
12
System.out.println("Here is main and a.getnumber() = "+a.getnumber());
13
}
14 }
範例29:設有檔案Ex04_5_2.java,其功能為解釋於類別程
序內,無法直接執行敘述式。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03
04
n = 3;
System.out.println("Here is Constructor and n = " + n);
05 int getnumber() { return n; }
06 }
07 class Ex04_5_2 {
08 public static void main(String[] args) {
09
Mynumber a = new Mynumber();
10
System.out.println("Here is main and a.getnumber() =
"+a.getnumber());
• 11
}
• 12 }
4-6方法程序重載(Method Overload)
• 當被呼叫執行時,參數型態與數量均符合的方法
程序,自動出面接受執行,如此物件行為是謂 “方
法程序重載(Method Overloading)”。
範例30:設有檔案Ex04_6_1.java,其功能為解釋方法程序重載之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class adder{
int add(int a,int b){return a+b;}
double add(double i,double j){return i+j;}
int add(int p, int q, int r) {return p+q+r;}
}
class Ex04_6_1{
public static void main(String[] args){
int c;
double k;
int s;
adder ad= new adder();
c=ad.add(1, 2);
System.out.println(“int c = ” + c);
k=ad.add(3.3, 4.4);
System.out.println(“double k = ” + k);
s=ad.add(5, 6, 7);
System.out.println("int s = " + s);
}
}
範例31:設有檔案Ex04_6_2.java,其功能為解釋建構子重載之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
class adder{
int c;
double k;
adder(int a, int b) {
c= a+b;
System.out.println("int c = "+ c);
}
adder(double i, double j){
k= i+j;
System.out.println("double k = "+ k);
}
}
class Ex04_6_2{
public static void main(String[] args){
adder add_int = new adder(2, 3);
adder add_double = new adder(2.2, 3.3);
}
}
4-7 public / private限制修飾子(Modifications)
• 在類別內宣告的變數(Variables)、或方法程序
(Methods) 均可前置限制修飾子(Modifications)
“public”、“private”,以限制其使用環境與時機
範例32:設有檔案Ex04_7_1.java,其功能為解釋變
數或方法程序前置限制修飾子public之應用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 public int i;
03 }
04 class Ex04_7_1 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Public Variable M.i = "+ M.i);
範例33:設有檔案Ex04_7_2.java,其功能為解釋變數或方
法程序前置限制修飾子private之錯誤應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int i;
03 }
04 class Ex04_7_2 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Private Variable M.i = "+ M.i);
範例34:設有檔案Ex04_7_3.java,其功能為解釋變數或方法程序
前置限制修飾子private時,只允許自身物件內之方法程序使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Study {
02 private int credit=0;
03 public void addcredit(int i) { credit += i; }
04 public int totalcredit() { return credit; }
05 }
06 class Ex04_7_3 {
07 public static void main(String[] args) {
08
Study joe = new Study();
09
Study george = new Study();
10
joe.addcredit(12);
11
george.addcredit(9);
12
joe.addcredit(6);
13
george.addcredit(3);
14
System.out.println("joe studied: "+joe.totalcredit()+"credites");
15
System.out.println("george studied:
"+george.totalcredit()+"credites");
• 16 }
• 17 }
4-8 this代名詞
• “this” 之功能除了是其本身類別代名詞外,亦可作
為重載建構子間之呼叫橋樑,將更增進資料的安
全性。
範例35:設有檔案Ex04_8_1.java,其功能為解釋this之應用,為所
屬類別物件(Class Objects) 之代名詞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
class Mynumber {
private int n;
public void setnumber(int i){this.n = i;}
public int getnumber(){return n;}
}
06
07
08
09
10
11
12
class Ex04_8_1 {
public static void main(String[] args) {
Mynumber M = new Mynumber();
M.setnumber(10);
System.out.println("M.getnumber : "+ M.getnumber());
}
}
範例36:比較範例35,設有檔案Ex04_8_2_1.java,其功能為解釋
this在建構子內,也是所屬類別物件之代名詞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03 public Mynumber(int i){this.n = i;}
04 public int getnumber(){return n;}
05 }
06 class Ex04_8_2_1 {
07 public static void main(String[] args) {
08
Mynumber M = new Mynumber(10);
09
System.out.println("M.getnumber : " + M.getnumber());
10 }
11 }
範例37:設有檔案Ex04_8_2_2.java,其功能為解釋於必要
時,this也是重載(Overload) 建構子的代名詞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03
04
public Mynumber(int i){this.n = i;}
public Mynumber(int j, String s){this(j);}
05 public int getnumber(){return n;}
06 }
07 class Ex04_8_2_2 {
08 public static void main(String[] args) {
09
Mynumber M = new Mynumber(10, "abcde");
10
System.out.println("M.getnumber : " + M.getnumber());
11 }
12 }
範例38:設有檔案Ex04_8_2_3.java,其功能為解釋當一個建構子以this() 呼叫另
一個重載建構子時,this() 必須置於該建構子的第一列。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03
04
05
06
07
public Mynumber(int i){this.n= i;}
public Mynumber(int j, String s){
System.out.println("Here is a Overload Constructor");
this(j);
}
08 public int getnumber(){return n;}
09 }
10 class Ex04_8_2_3 {
11 public static void main(String[] args) {
12
Mynumber M = new Mynumber(10, "abcde");
13
System.out.println("M.getnumber : " + M.getnumber());
14 }
15 }
4-9 巢狀類別(Nested Class)
•
• 設有類別A、類別B,如果B存在於A之範圍內,則
B是A之 “次類別(Sub Class或Inner Class)”。如此排
列稱為 “巢狀類別(Nested Classes)”。
範例39:設有檔案Ex04_9_1_1.java,其功能為解釋成員類別程序
(Member Class) 產生新物件之步驟。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
13
14
15
16
17
18
19
20
21
22
23
class MyClass {
class memb1 {
int i;
void seti() {i = 10;}
int geti() {return i;}
}
class memb2 {
int i;
void seti() {i = 20;}
int geti() {return i;}
}}
class Ex04_9_1_1 {
public static void main(String[] args) {
MyClass M = new MyClass();
MyClass.memb1 m1 = M.new memb1();
m1.seti();
System.out.println(“m1.geti : ”+ m1.geti());
MyClass.memb2 m2 = M.new memb2();
m2.seti();
System.out.println("m2.geti : "+ m2.geti());
}
}
範例40:設有檔案Ex04_9_1_2.java,其功能為解釋修飾子
public/private與成員類別之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
13
14
15
16
17
18
19
20
21
22
class MyClass {
public class memb1 {
int i;
void seti() {i = 10;}
int geti() {return i;}
}
private class memb2 {
int i;
void seti() {i = 20;}
int geti() {return i;}
} }
class Ex04_9_1_2 {
public static void main(String[] args) {
MyClass M = new MyClass();
MyClass.memb1 m1 = M.new memb1();
m1.seti();
System.out.println(“m1.geti : ”+ m1.geti());
MyClass.memb2 m2 = M.new memb2();
m2.seti();
System.out.println("m2.geti : "+ m2.geti());
}}
範例40:設有檔案Ex04_9_1_2.java,其功能為解釋修飾子
public/private與成員類別之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
13
14
15
16
17
18
19
20
21
22
class MyClass {
public class memb1 {
int i;
void seti() {i = 10;}
int geti() {return i;}
}
private class memb2 {
int i;
void seti() {i = 20;}
int geti() {return i;}
}}
class Ex04_9_1_2 {
public static void main(String[] args) {
MyClass M = new MyClass();
MyClass.memb1 m1 = M.new memb1();
m1.seti();
System.out.println(“m1.geti : ”+ m1.geti());
MyClass.memb2 m2 = M.new memb2();
m2.seti();
System.out.println("m2.geti : "+ m2.geti());
}}
範例41:設有檔案Ex04_9_1_3.java,其功能為解釋成員類別與宣告變數之關係。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_9_1_3 {
02
int i,j;
03
private MyMember memb;
04
class MyMember {
05
int m,n,o;
06
MyMember() {
07
i = 2;
08
Ex04_9_1_3.this.j = 4;
09
m = 12;
10
this.n = 14;
11
MyMember.this.o = 16;
12
}
13
public int getO() { return o; }
14
}
15
public Ex04_9_1_3 () {
16
memb = new MyMember();
17
System.out.println("m= "+memb.m + ","+
18
"n= "+memb.n + ","+
19
"o= "+memb.getO());
20
}
21
public int getJ() { return j; }
22
public static void main(String[] args) {
23
Ex04_9_1_3 a = new Ex04_9_1_3 ();
24
System.out.println("i= "+a.i +","+
25
"j= "+a.getJ());
26
}}
範例42:設有檔案Ex04_9_2_1.java,其功能為解釋區域類別與生
存區塊之關係。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_9_2_1 {
02 int i;
03 public Ex04_9_2_1() {
04
class MyLocal {
05
int j;
06
public MyLocal(){
07
i = 5;
08
j= 10;
09
}
10
}
11
MyLocal L = new MyLocal();
12 }
13 public static void main(String[] args) {
14
Ex04_9_2_1 M = new Ex04_9_2_1();
15
System.out.println("j of Local: "+L.j);
16
System.out.println("i of Ex04_9_2_1: "+ M.i);
17 }
18 }
範例43:更正範例42,設有檔案Ex04_9_2_2.java,其功能為解釋
區域類別與生存區塊之關係。
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_9_2_2 {
02 int i;
03 public Ex04_9_2_2() {
04
class MyLocal {
05
int j;
06
public MyLocal(){
07
i = 5;
08
j= 10;
09
} }
11
MyLocal L = new MyLocal();
12
System.out.println("j of Local: "+L.j);
•
•
•
•
•
13 }
14 public static void main(String[] args) {
15
Ex04_9_2_2 M = new Ex04_9_2_2();
16
System.out.println("i of Ex04_9_2_2: "+ M.i);
17 } }
範例44:設有檔案Ex04_9_2_3.java,其功能為解釋區域類
別不宜前置public、private等存取設定。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_9_2_3 {
02 int i;
03 public Ex04_9_2_3() {
04
public class MyLocal {
05
int j;
06
public MyLocal(){
07
i = 5;
08
j= 10;
09
}
10
}
11
MyLocal L = new MyLocal();
12
System.out.println("j of Local: "+L.j);
13 }
14 public static void main(String[] args) {
15
Ex04_9_2_3 M = new Ex04_9_2_3();
16
System.out.println("i of Ex04_9_2_3: "+ M.i);
17 }
18 }
第五章
基礎程式設計(Basic Programming)
•
•
•
•
•
•
•
•
•
•
•
5-1 簡介
5-2繼承(Inheritance)
5-3 繼承(Inheritance) 與 限制修飾子(Modifications)
5-4 super之應用
5-5 final之應用
5-6 抽象類別(Abstract Classes)
5-7 介面類別(Interface Classes)
5-8 多重型態(Polymorphism)
5-9 習題(Exercises)
5-1 簡介
• 本章重點在繼承類別(Inheritance)、抽象類別
(Abstract)、與介面類別(Interface),介紹類別物件
間之關係,將我們人類之邏輯思維灌溉在程式字
裡行間,使電腦以我們熟悉的方法來解決問題。
5-2繼承(Inheritance)
• 當一個類別B繼承(Inheritance) 自另一個類別A時,
前者B為子類別(Sub Class ),後者A為父類別
(Supper Class),子類別B繼承父類別A所擁有之所
有內容內涵(如範例45)。
範例45:設有檔案Ex05_2_1.java,其功能為解釋子類別繼承父類
別時,子類別將擁有父類別所有之功能內涵。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
class E extends MyNumber {}
class Ex05_2_1 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
範例46:設有檔案Ex05_2_2.java,其功能為解釋當子類別繼承自父類別時,子類
別除了繼承父類別所擁有之內涵外,還可另添加本身之特性內涵。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class MyNumber {
private int number;
public void setNumber(int i) { number = i; }
public int getNumber() { return number; }
}
class E extends MyNumber {
private String string;
public void setString(String s) { string = s; }
public String getString() { return string; }
}
class Ex05_2_2 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
a.setString(“I am in the SubClass”);
System.out.println("The number of a is: "+a.getNumber());
System.out.println("The string of a is: "+a.getString());
}
}
範例47:設有檔案Ex05_2_3.java,其功能為解釋當子類別的內容與父類
別的內容有衝突時,子類別之內容將覆蓋(Overwrite) 父類別之內容。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 int number;
03 public void setNumber() { number = 5; }
04 public int getNumber() { return number; }
05 }
06 class E extends MyNumber {
07 public void setNumber() { number = 10; }
08 }
09 class Ex05_2_3 {
10 public static void main(String[] args) {
11
E a = new E();
12
a.setNumber();
13
System.out.println("The number of a is: "+a.getNumber());
14 }
15 }
5-3 繼承(Inheritance) 與 限制修飾子
(Modifications)
•
• 如4-7節曾述,變數與方法程序均有Public/Private
的使用限制。本節以Public/Private/protected,介
紹修飾子(Modifications) 在父類別與子類別繼承上
之限制
範例48:設有檔案Ex05_3_1.java,其功能為解釋父類別之變數前
置public,當被子類別繼承時,該變數可在子類別內被使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {public int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex05_3_1 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is:
"+a.getNumber());
• 11 }
• 12 }
範例49:參考範例48,設有檔案Ex05_3_2.java,其功能為解釋父
類別之變數前置private,不得在子類別內被使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {private int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex05_3_2 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is:
"+a.getNumber());
• 11 }
• 12 }
範例50:參考範例48,設有檔案Ex05_3_3.java,其功能為解釋父類別之
變數前置protected,可被同一包裹內之類別採用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {protected int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex05_3_3 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is:
"+a.getNumber());
• 11 }
• 12 }
5-4 super之應用
•
• super為父類別的代名詞,在執行super() 時,是直
指父類別之建構子(如範例51)。
範例51:設有檔案Ex05_4_1.java,其功能為解釋super() 為呼叫並
執行父類別之建構子。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
class myNumber {
private int number;
myNumber (int number) {this.number = number;}
public int getNumber() { return number; }
}
class E extends myNumber {
E() {super(5);}
}
class Ex05_4_1 {
public static void main(String[] args) {
E a = new E();
System.out.println("number= "+a.getNumber());
}
}
範例52:設有檔案Ex05_4_2.java,其功能為解釋如果子類別建構
子內未設置super(),系統會於第一列自動加一行隱藏的super()。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class A {
A() {
System.out.println("A's constructor");}
}
class B extends A {
B() {
System.out.println("B's constructor");}
}
class C extends B {
C() {
System.out.println("C's constructor");}
}
class Ex05_4_2 {
public static void main(String[] args) {
C c = new C();
}
}
5-5 final之應用
• 顧名思義,final之意義為 “最後者”,不得再繼續
變化使用,可前置於類別程序、方法程序、變數
範例53:設有檔案Ex05_5_1.java,其功能為解釋當final前置於類別
程序時,該類別程序不得被繼承。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
final class myNumber {
int number= 5;
}
class E extends myNumber{
int number= 10;
public int getsuperNumber() {return super.number;}
public int getthisNumber() {return this.number;}
}
class Ex05_5_1 {
public static void main(String[] args) {
E a = new E();
System.out.println("The myNumber_number of a is: "
+a.getsuperNumber());
13
System.out.println("The E_number of a is: "+a.getthisNumber());
14 }
15 }
範例54:設有檔案Ex05_5_2.java,其功能為解釋當final前置於方法
程序時,該方法程序不得被覆蓋。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 int number;
03 final void setNumber() { number = 5; }
04 public int getNumber() { return number; }
05 }
06 class E extends MyNumber {
07 public void setNumber() { number = 10; }
08 }
09 class Ex05_5_2 {
10 public static void main(String[] args) {
11
E a = new E();
12
a.setNumber();
13
System.out.println("The number of a is: "+a.getNumber());
14 }
15 }
範例55:設有檔案Ex05_5_3.java,其功能為解釋當final前
置於變數時,該變數只可被設定一次。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_5_3 {
02 public static void main (String[] argv) {
03
final int i = 5;
04
final int j;
05
06
i = 10;
j = 20;
07
j = 30;
08
System.out.println("i = "+ i);
09
System.out.println("j = "+ j);
10 }
11 }
5-6 抽象類別(Abstract Classes)
•
• 抽象類別(Abstract Classes) 代表對某項內涵之關切
,在程式流程上不必亦無法執行該內涵,但在程
式總體上有如此一份內涵之地位。
範例56:設有檔案Ex05_6_1.java,其功能為解釋抽象類別(Abstract
Classes) 不得用於產生新物件。
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
private int number = 5;
03
public int getNumber() { return number; }
04 }
05 class Ex05_6_1 {
06 public static void main(String[] args) {
07
myNumber a = new myNumber();
08
System.out.println(a.getNumber());
09 }
10 }
範例57:設有檔案Ex05_6_2.java,其功能為解釋抽象類別用
於被繼承,由繼承之子類別產生新物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
private int number = 5;
03
public int getNumber() { return number; }
04 }
05 class E extends myNumber {}
06 class Ex05_6_2 {
07 public static void main(String[] args) {
08
E a = new E();
09
System.out.println("the number of a= "+a.getNumber());
10 }
11 }
範例58:設有檔案Ex05_6_3.java,其功能為解釋抽象方法
程序不得有程式碼內容。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber() {return number;};
04 }
05 class E extends myNumber {}
06 class Ex05_6_3 {
07 public static void main(String[] args) {
08
E a = new E();
09
System.out.println("the number of a= "+a.getNumber());
10 }
11 }
範例59:設有檔案Ex05_6_4.java,其功能為解釋於繼承之子類別,應有
一對應之方法程序,具有程式碼內容,執行抽象方法程序功能。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber();
04 }
05 class E extends myNumber {
06 public int getNumber() {return number;}
07 }
08 class Ex05_6_4 {
09 public static void main(String[] args) {
10
E a = new E();
11
System.out.println("the number of a= "+a.getNumber());
12 }
13 }
範例60:設有檔案Ex05_6_5.java,其功能為解釋凡有抽象方法程
序之類別,必須前置abstract。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber();
04 }
05 class E extends myNumber {
06 public int getNumber() {return number;}
07 }
08 class Ex05_6_5 {
09 public static void main(String[] args) {
10
E a = new E();
11
System.out.println("the number of a= "+a.getNumber());
12 }
13 }
5-7 介面類別(Interface Classes)
• 介面類別的功能型態猶如抽象類別,不得直接用
於以 “new” 產生新物件,亦不得讓其他類別直接
在此匯集,如同抽象類別是一種內涵之關切
範例61:設有檔案Ex05_7_1.java,其功能為解釋介面之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF {public void f();}
02 class A implements myITF {
03 public void f() {System.out.println("myITF");}
04 }
05 class Ex05_7_1 {
06 public static void main(String[] args) {
07
A a = new A();
08
a.f();
09 }
10 }
範例62:設有檔案Ex05_7_2.java,其功能為解釋同時以
extends繼承類別程序、以implements承作介面。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF {public void f();}
02 class myNumber {
03 public void g() {System.out.println("In myNumber");}
04 }
05 class A extends myNumber implements myITF {
06 public void f() {System.out.println("In myITF");}
07 }
08 class Ex05_7_2 {
09 public static void main(String[] args) {
10
A a = new A();
11
a.f();
12
a.g();
13 }
14 }
範例63:設有檔案Ex05_7_3.java,其功能為解釋一個類別可同時
承作(implements) 多個介面類別。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF1 {public void f();}
02 interface myITF2 {public void g();}
03 class A implements myITF1, myITF2 {
04 public void f() {System.out.println("In myITF1");}
05 public void g() {System.out.println("In myITF2");}
06 }
07 class Ex05_7_3 {
08 public static void main(String[] args) {
09
A a = new A();
10
a.f();
11
a.g();
12 }
13 }
範例64:設有檔案Ex05_7_4.java,其功能為解釋介面內之方法程序必須
均無內容程式碼,且子類別內對應之方法程序,必須另加置內容程式碼
。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myNumber {
02 public int number= 5;
03 public void setprint();
04 public int getNumber();
05 }
06 class E implements myNumber {
07 public void setprint() {System.out.println("In E");}
08 public int getNumber() {return number;}
09 }
10 class Ex05_7_4 {
11 public static void main(String[] args) {
12
E a = new E();
13
a.setprint();
14
System.out.println("the number of a= "+a.getNumber());
15 }
16 }
5-8 多重型態(Polymorphism)
• 資料型態與實體模型不屬同一類別時,是謂 “多重
型態(Polymorphism)”,是一種不正常的扭曲型態
範例65:設有檔案Ex05_8_1.java,其功能為解釋多
重型態(Polymorphism) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void f() {System.out.println("In myClass2");
07 }
08 }
09 class Ex05_8_1 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.f();
13 }
14 }
範例66:設有檔案Ex05_8_2.java,其功能為解釋若資料型態類別內有符合名稱之
方法程序,而實體模型類別內無時,則執行資料型態類別內之方法程序。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In f of myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void g() {System.out.println("In g of myClass2");
07 }
08 }
09 class Ex05_8_2 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.f();
13 }
14 }
範例67:設有檔案Ex05_8_3.java,其功能為解釋若資料型態類別內無符合名稱之
方法程序,雖實體模型類別內有,則仍不作任何執行。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In f of myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void g() {System.out.println("In g of myClass2");
07 }
08 }
09 class Ex05_8_2 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.g();
13 }
14 }
第六章
例外處理(Exceptions)
•
•
•
•
•
•
•
•
•
•
•
6-1 簡介
6-2 try / catch / finally區段
6-2-1 try/catch區段之必要性
6-2-2 try/catch區段之應用
6-2-3 finally區段之應用
6-3 throws之用法
6-4 自訂例外處理物件
6-4-1以內建例外處理類別產生自訂新物件
6-4-2以自訂例外處理類別產生自訂新物件
6-5 習題(Exercises)
6-1 簡介
•
• 執行Java程式時,若遇錯誤程式碼,Java即以例外
處理機制處理,並顯示錯誤警語,提醒程式設計
師有關事宜。
6-2 try / catch / finally區段
•
• 於Java類別程式區塊內(除了一般程式碼區域外) 可
分割成數個特定意義的區段:(1)凡影響系統作業
的程式碼必須要在 “try區段” 執行;(2)如果try區
段有引發編譯錯誤的程式碼、或引發錯誤的邏輯
行為,則由 “catch區段” 捕捉其錯誤、顯示其錯誤
訊息、及停止程式繼續執行;(3) “finally區段” 之
程式碼為必須要執行的流程。
•
範例68:設有檔案Ex06_2_1_1.java,其功能為解
釋建立網站與try/catch之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex06_2_1_1 {
04 ServerSocket SS;
05 public Ex06_2_1_1() {
06
SS = new ServerSocket(1234);
07
System.out.println("Server created.");
08 }
09 public static void main(String args[]){
10
Ex06_2_1_1 ServerStart=new Ex06_2_1_1();
11 }
12 }
範例69:設有檔案Ex06_2_1_2.java,其功能為解釋建立網
站與try/catch之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
import java.net.*;
import java.io.*;
public class Ex06_2_1_2 {
ServerSocket SS;
public Ex06_2_1_2() {
try{
SS = new ServerSocket(1234);
System.out.println("Server created.");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
Ex06_2_1_2 ServerStart=new Ex06_2_1_2();
}
}
範例70:設有檔案Ex06_2_2_1.java,其功能為解
釋不設try/catch區段之應用。
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_2_1 {
02 public static void main (String args[])
03
{
04
int x;
05
06
07
08 }
x = 10 / 0;
System.out.println("x= "+ x);
}
範例71:比較範例70,設有檔案Ex06_2_2_2.java,其功能
為解釋try/catch區段與例外事件資料庫之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_2_2 {
02 public static void main (String args[]) {
03
int x;
04
05
06
07
try {
x = 10 / 0;
System.out.println("x= "+ x);
}
08
catch (ArithmeticException e) {
09
System.out.println("In ArithmeticException:"+e.getMessage());
10
}
11 }
12 }
範例72:比較範例71,設有檔案Ex06_2_2_2.java,其功能為解釋
catch區段以Exception取代ArithmeticException之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_2_3 {
02 public static void main (String args[]) {
03
int x;
04
try {
05
x = 10 / 0;
06
System.out.println("x= "+ x);
07
}
08
catch (Exception e) {
09
System.out.println("In Exception :"+e.getMessage());
10
}
11 }
12 }
範例73:比較範例72,設有檔案Ex06_2_3_1.java,其功能
為解釋finally區段之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_3_1 {
02 public static void main (String args[]) {
03
int x;
04
05
06
07
try {
x = 10 / 0;
System.out.println("x= "+ x);
}
08
09
10
catch (Exception e) {
System.out.println("In Exception :"+e.getMessage());
}
11
finally {
12
System.out.println("In finally");
13
}
14 }
15 }
範例74:參考範例73,設有檔案Ex06_2_3_2.java,其功能為解釋依圖6-2項3,設
置try區段,不設置catch區段,如果加置finally區段也可能編譯成功。
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_3_2 {
02 public static void main (String args[]) {
03
int x;
04
try {
05
x = 10 / 0;
06
System.out.println("x= "+ x);
07
}
08
}
09 }
範例75:參考範例69,設有檔案Ex06_2_3_3.java,其功能為解釋依圖6-2項3,設
置try區段,不設置catch區段,如果加置finally區段也可能編譯不成功。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex06_2_3_3 {
04 ServerSocket SS;
05 public Ex06_2_3_3() {
06
try{
07
SS = new ServerSocket(1234);
08
System.out.println("Server created.");
09
}
10 public static void main(String args[]){
11
Ex06_2_3_3 ServerStart=new Ex06_2_3_3();
12 }
13 }
6-3 throws之用法
•
• 前節曾述及,Java使用try/catch區段捕捉例
外事件,尤其在處理重要事件時,為了系
統安全,更是要求程式碼必須要置於
try/catch區段內執行,否則將發生編譯錯誤
。
範例76:參考範例68、範例69,設有檔案Ex06_3_1.java,其功能
為解釋方法程序或建構子宣告 “throws” 以取代try/catch之使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex06_3_1 {
04 ServerSocket SS;
05 public Ex06_3_1() throws IOException {
06
SS = new ServerSocket(1234);
07
System.out.println("Server created.");
08 }
09 public static void main(String args[]) throws IOException{
10
Ex06_3_1 ServerStart=new Ex06_3_1();
11 }
12 }
範例77:參考範例70、範例71,設有檔案
Ex06_3_2.java,其功能為解釋方法程序或建構子宣
告 “throws” 以取代try/catch之使用。
•
• 01 class Ex06_3_2 {
• 02 public static void main (String args[]) throws
ArithmeticException {
• 03
int x;
• 04
x = 10 / 0;
• 05
System.out.println("x= "+ x);
• 06 }
• 07 }
6-4 自訂例外處理物件
• 自訂例外處理物件可分為:(1)以內建例外處理類
別產生自訂新物件;(2)自訂例外處理類別產生自
訂新物件。
範例78:參考範例71,設有檔案Ex06_4_1_1.java,其功能為解釋
自訂匿名新例外處理物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_1_1 {
02 public static void main (String args[]) {
03
int x, y;
04
05
06
07
08
09
10
try {
x = 10;
y = 0;
if(y==0) throw new ArithmeticException("DIY Message");
x = 10 / 0;
System.out.println("x= "+ x);
}
11
catch (ArithmeticException e){
12
System.out.println("In ArithmeticException:"+e.getMessage());
13
}
14 }
15 }
範例79:參考範例78,設有檔案Ex06_4_1_2.java,其功能
為解釋自訂具名新例外處理物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_1_2 {
02 public static void main (String args[]) {
03
ArithmeticException f = new ArithmeticException("DIY Message");
04
int x, y;
05
06
07
08
09
10
try {
x = 10;
y = 0;
x = 10 / 0;
System.out.println("x= "+ x);
}
11
catch (ArithmeticException e){
12
System.out.println("In Built Message: "+e.getMessage());
13
System.out.println("In DIY Message: "+f.getMessage());
14
}
15 }
16 }
範例80:參考範例78,設有檔案Ex06_4_2_1.java,其功能為解釋
自訂預定訊息例外處理類別與匿名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
class myException extends Exception {
myException() {
super("myException Message");
}
}
class Ex06_4_2_1 {
public static void main (String args[]) {
int x, y;
try {
x = 10;
y = 0;
if(y==0) throw new myException();
x = 10 / 0;
System.out.println("x= "+ x);
}
catch (myException e){
System.out.println("In myException: "+e.getMessage());
}
}
}
範例81:參考範例79,設有檔案Ex06_4_2_2.java,其功能
為解釋自訂預定訊息例外處理類別與具名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
class myException extends Exception {
myException() {
super("myException Message");
}
}
class Ex06_4_2_2 {
public static void main (String args[]) {
myException f = new myException();
int x, y;
try {
x = 10;
y = 0;
x = 10 / 0;
System.out.println("x= "+ x);
}
catch (ArithmeticException e){
System.out.println("In Built Message: "+e.getMessage());
System.out.println("In myException Message: "+f.getMessage());
}
}
}
範例82:參考範例80,設有檔案Ex06_4_2_3.java,其功能
為解釋自訂機動訊息例外處理類別與匿名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
class myException extends Exception {
myException(String msg) {
super(msg);
}
}
class Ex06_4_2_3 {
public static void main (String args[]) {
int x, y;
try {
x = 10;
y = 0;
if(y==0) throw new myException("DIY Message");
x = 10 / 0;
System.out.println("x= "+ x);
}
catch (myException e){
System.out.println("In myException: "+e.getMessage());
}
}
}
範例83:參考範例81,設有檔案Ex06_4_2_4.java,其功能為解釋
自訂機動訊息例外處理類別與具名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
class myException extends Exception {
myException(String msg) {
super(msg);
}
}
class Ex06_4_2_4 {
public static void main (String args[]) {
myException f = new myException(“DIY Message”);
int x, y;
try {
x = 10;
y = 0;
x = 10 / 0;
System.out.println("x= "+ x);
}
catch (ArithmeticException e){
System.out.println("In Built Message: "+e.getMessage());
System.out.println("In myException Message: "+f.getMessage());
}
}
}
第七章
Package包裹與Jar檔案
•
•
•
•
•
•
•
•
•
•
•
•
•
7-1 簡介
7-2類別(Class) 檔案
7-3 單一檔案包裹(Single File Package)
7-4 多檔案包裹(Multi Files Package)
7-5包裹匯入(Import Package)
7-6壓縮檔案(jar Files)
7-7 jar檔與class檔之加入
7-7-1 包裹class檔
7-7-2 非包裹class檔
7-8 使用jar檔
7-8-1 匯入jar檔
7-8-2 jar檔新物件
7-9 習題(Exercises)
7-1 簡介
•
• Java於程式設計時,可依需要設定package包裹,
將一個Java程式、或多個功能相同的Java程式,歸
置於一個包裹內
• Java可將package包裹壓縮成jar檔案
7-2類別(Class) 檔案
•
• 當Java程式經過編譯後,程式內的每一類別
都將各自產生一個xxx.class檔案,如前述,
如此每一個class檔案就是一個物件。
範例84:設有檔案Ex07_2_1.java,其功能為解釋在Java程式諸多
class類別中,僅允許其中主體類別可前置public。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
public class E extends MyNumber {}
public class Ex07_2_1 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
範例85:設有檔案Ex07_2_2.java,其功能為解釋當Java程式經過編
譯後,程式內的每一類別都將各自產生一個xxx.class檔案。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
class E extends MyNumber {}
public class Ex07_2_2 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
7-3 單一檔案包裹(Single File Package)
• Java可於程式設計時,依需要設定package
包裹,同一包裹內的類別在編譯完成後,
將共同歸置於同一目錄內,如此既易管理
亦易儲存。
範例86:設有檔案Ex07_3.java,其功能為解釋於單一程式檔案中
,如何建立包裹?如何編譯包裹?如何執行包裹?。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
class E extends MyNumber {}
public class Ex07_3 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
7-4 多檔案包裹(Multi Files Package)
•
• 為了方便管理,我們可將多個Java程式檔案
,以編譯方式將各個類別程序,編譯成class
檔案,置入同一包裹內。
範例87:設有檔案Ex07_4.java與MyNumber.java,其功能為
解釋於多個程式檔案中,如何建立共同包裹?如何編譯共
同包裹?如何執行共同包裹?。
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案MyNumber.java:
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例87:續
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Ex07_4.java:
11 package myPackage;
12 class E extends MyNumber {}
13 public class Ex07_4 {
14 public static void main(String[] args) {
15 E a = new E();
16 a.setNumber(5);
17 System.out.println("a=: "+a.getNumber());
18 }
19 }
7-5包裹匯入(Import Package)
•
• 在設計Java程式中,為了設計簡便,也可以
使用別人已設計完成的包裹。
範例88:設有檔案Ex07_5.java與MyNumber.java,
其功能為解釋包裹匯入之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案MyNumber.java:
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例88:續
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Ex07_5.java:
01 import myPackage.MyNumber;
02 class E extends MyNumber {}
03 public class Ex07_5 {
04 public static void main(String[] args) {
05 E a = new E();
06 a.setNumber(5);
07 System.out.println("a=: "+a.getNumber());
08 }
09 }
7-6壓縮檔案(jar Files)
• 當Java程式經過編譯後,程式內的各類別將
各自產生成xxx.class檔,系統再將各class檔
壓縮後儲存於jar檔案內。
範例89:設有檔案Ex07_6.java,其功能為解釋如何建立包裹?如
何建立jar檔?如何執行jar檔?。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
11 class E extends MyNumber {}
12 public class Ex07_6 {
13 public static void main(String[] args) {
14 E a = new E();
15 a.setNumber(5);
16 System.out.println("a=: "+a.getNumber());
17 }
18 }
7-7 jar檔與class檔之加入
• 本節將介紹如何將一個class檔壓縮加入jar
檔?
範例90:設有檔案Ex07_7_1.java其功能為解釋將包裹內的
class檔加入jar檔。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
class E extends MyNumber {}
public class Ex07_7_1 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
範例91:設有檔案Ex07_7_2.java其功能為解釋將非包裹內
的class檔加入jar檔。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class MyNumber{
private int number;
public void setNumber(int i) {
number = i;
}
public int getNumber() {
return number;
}
}
class E extends MyNumber {}
public class Ex07_7_2 {
public static void main(String[] args) {
E a = new E();
a.setNumber(5);
System.out.println("a=: "+a.getNumber());
}
}
7-8 使用jar檔
•
• 我們已實作如何建立jar檔,讀者以後在Java
程式設計上,將會開發jar檔提供給其他程
式使用;或是讀者自己在設計程式時,使
用到別人開發的jar檔。
範例92:設有檔案Ex07_8_1.java與MyNumber.java,其功能
為解釋匯入jar檔案之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案MyNumber.java:
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例92:續
•
•
•
•
•
•
•
•
•
•
•
•
檔案Ex07_8_1.java:
01 import myPackage.*;
02 public class Ex07_8_1 {
03 public static void main(String[] args) {
04
MyNumber a = new MyNumber();
05 a.setNumber(5);
06 System.out.println("a=: "+a.getNumber());
07 }
08 }
範例93:設有檔案Ex07_8_2.java與MyNumber.java
,其功能為解釋jar檔新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案MyNumber.java:
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例93:續
•
•
•
•
•
•
•
•
•
檔案Ex07_8_2.java:
01 public class Ex07_8_2 {
02 public static void main(String[] args) {
03 myPackage.MyNumber a = new
myPackage.MyNumber();
04 a.setNumber(5);
05 System.out.println("a=: "+a.getNumber());
06 }
07 }
第八章
輸入輸出串流(Input/Output Streams)
•
•
•
•
•
•
•
•
•
•
8-1 簡介
8-2 指令參數(Command Parameters)
8-3 檔案物件(File Objects)
8-4 檔案輸入輸出串流(File Input/Output Streams)
8-5 FileInputStream與FileOutputStream
8-6 DataInputStream與DataOutputStream
8-7 FileReader與FileWriter
8-8鍵盤資料輸入
8-9 習題(Exercises)
8-1 簡介
• 在資料傳輸上,我們可將電腦的週邊設備(如印表
機、螢幕、磁碟等) 視為是檔案,資料從一個檔案
傳送到另一個檔案,甚至可將範圍擴大到無遠弗
屆的網路上。
8-2 指令參數(Command Parameters)
•
• 到目前為止,我們不曾對範例程式直接輸入訊息
,於Java程式,我們可利用指令參數(Command
Parameters) 直接輸入訊息。
範例94:設有檔案Ex08_2_1.java,其功能為解釋字串指令
參數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex08_2_1 {
02 static String msg;
03
04
05
Ex08_2_1() {
System.out.println(msg);
}
06 public static void main(String[] args) {
07
msg = args[0];
08
Ex08_2_1 a = new Ex08_2_1();
09 }
10 }
範例95:設有檔案Ex08_2_2.java,其功能為解釋整數指令
參數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex08_2_2 {
02 static int num;
03
04
05
06
Ex08_2_2() {
num = num+1;
System.out.println(num);
}
07 public static void main(String[] args) {
08
num = Integer.parseInt(args[0]);
09
Ex08_2_2 a = new Ex08_2_2();
10 }
11 }
範例96:設有檔案Ex08_2_3.java,其功能為解釋指令參數訊息之
應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex08_2_3 {
02 static String msg;
03 static int num;
04
05
06
07
Ex08_2_3() {
System.out.println(msg);
System.out.println(num);
}
08 public static void main(String[] args) {
09
if(args.length < 2) {
10
System.out.println("Usage: java Ex08_2_3 [msg] [num]");
11
System.exit(1);
12
}
13
msg = args[0];
14
num = Integer.parseInt(args[1]);
15
Ex08_2_3 a = new Ex08_2_3();
16 }
17 }
8-3 檔案物件(File Objects)
•
• Java系統之java.io有其內建之檔案類別File.class,
我們只要於程式檔案加入import java.io.File,即可
以此類別產生新檔案物件
範例97:設有檔案Ex08_3_1.java,其功能為解釋檔案物件
之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.File;
02 class Ex08_3_1 {
03 public static void main(String args[]) {
04
if (args.length < 1) {
05
System.out.println("Usage: java Ex08_3_1 [fileName]");
06
System.exit(1);
07
}
08
09
String fileName = args[0];
File f = new File(fileName);
10
System.out.println("The File is: ");
11
System.out.println(" File Name: " + f.getName());
12 }
13 }
範例98:設有檔案Ex08_3_2.java,其功能為解釋檔案物件方法程序與例外事件處
理之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.File;
import java.util.Date;
class Ex08_3_2 {
public static void main(String args[]) throws java.io.IOException {
if (args.length < 1) {
System.out.println("Usage: java Ex08_3_2 [fileName]");
System.exit(1);
}
String fileName = args[0];
File f = new File(fileName);
System.out.println("The File is: ");
System.out.println(" File Name: " + f.getName());
System.out.println(" File Name: " + f.getName());
System.out.println(" Canonical File Name: " + f.getCanonicalFile());
System.out.println(" canWritable: " + f.canWrite());
System.out.println(" Length: " + f.length());
System.out.println(" Hidden: " + f.isHidden());
System.out.println(" isFile: " + f.isFile());
System.out.println(" isDirectory: " + f.isDirectory());
System.out.println(" LastModified: " + new Date(f.lastModified()));
}}
8-4 檔案輸入輸出串流(File Input/Output Streams)
• Java程式之輸入輸出串流類別繼承自:(1)
InputStream/OutputStream、與(2) Reader/Writer,
前者用於位元傳輸,以位元組(Bytes) 為傳輸單位
;後者以字元(Character) 為傳輸單位,適用於以
Unicode編碼之文字(如中文等亞洲語系)。
8-5 FileInputStream與FileOutputStream
•
• 如附錄C,類別FileInputStream繼承自InputStream
;類別FileOutputStream繼承自OutputStream,用
於檔案資料傳遞。
範例99:設有檔案Ex08_5_1.java,其功能為解釋FileInputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_5_1 {
03 public static void main(String args[]) throws Exception {
04
int i;
05
06
07
08
if (args.length < 1) {
System.out.println("Usage: java Ex08_5_1 [fileName]");
System.exit(1);
}
09
10
String fileName = args[0];
FileInputStream fis=new FileInputStream(fileName);
11
while((i = fis.read()) != -1) {
12
System.out.print((char)i);
13
}
14 }
15 }
範例100:設有檔案Ex08_5_2.java,其功能為解釋FileOutputStream
之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_5_2 {
03 public static void main(String args[]) throws Exception {
04
if (args.length < 1) {
05
System.out.println("Usage: java Ex08_5_2 [fileName]");
06
System.exit(1);
07
}
08
09
String fileName = args[0];
FileOutputStream fos=new FileOutputStream(fileName);
10
String line = "Test for FileOutputStream 中文測試";
11
fos.write(line.getBytes());
12
fos.close();
13 }
14 }
範例101:設有檔案Ex08_5_3.java,其功能為解釋以FileInputStream /
FileOutStream將一個檔案之內容傳遞至另一個檔案內。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_5_3 {
03 public static void main(String args[]) throws Exception {
04 int i;
05 if (args.length < 2) {
06
System.out.println("Usage: java Ex08_5_3 [infileName] [outfileName]");
07
System.exit(1);
08 }
09 String infileName = args[0];
10 String outfileName = args[1];
11 FileInputStream fis=new FileInputStream(infileName);
12 FileOutputStream fos=new FileOutputStream(outfileName);
13 while((i=fis.read()) !=-1) {
14
fos.write(i);
15 }
16 }
}
8-6 DataInputStream與DataOutputStream
•
• 使用DataInputStream / DataOutputStream時,須與
其父類別FileInputStream / FileOutputStream 搭配
使用。
範例102:設有檔案Ex08_6_1.java,其功能為解釋FileInputStream /
DataInputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_6_1 {
03 public static void main(String args[])throws Exception {
044 int i;
05 if (args.length < 1) {
06
System.out.println("Usage: java Ex08_6_1 [fileName]");
07
System.exit(1);
08 }
09 String fileName = args[0];
10 FileInputStream fis=new FileInputStream(fileName);
11 DataInputStream dis = new DataInputStream(fis);
12 while((i=dis.read()) !=-1) {
13
System.out.print((char)i);
14 }
15 }
16 }
範例103:設有檔案Ex08_6_2.java,其功能為解釋
FileOutputStream / DataOutputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_6_2 {
03 public static void main(String args[])throws Exception {
04 if (args.length < 1) {
05
System.out.println("Usage: java Ex08_6_2 [fileName]");
06
System.exit(1);
07 }
08
09
10
String fileName = args[0];
FileOutputStream fos=new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos);
11 String line= "Test for DataOutputStream 中文測試";
12 dos.write(line.getBytes());
13 dos.close();
14 }
15 }
範例104:設有檔案Ex08_6_3.java,其功能為解釋以FileInputStream / DataInputStream、
FileOutStream / DataOutputStream將一個檔案之內容傳遞至另一個檔案內。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_6_3 {
03 public static void main(String args[])throws Exception {
04 int i;
05 if (args.length < 2) {
06
System.out.println("Usage: java Ex08_6_3 [infileName] [outfileName]");
07
System.exit(1);
08 }
09 String infileName = args[0];
10 String outfileName = args[1];
11 FileInputStream fis=new FileInputStream(infileName);
12 DataInputStream dis = new DataInputStream(fis);
13
14
FileOutputStream fos=new FileOutputStream(outfileName);
DataOutputStream dos = new DataOutputStream(fos);
15 while((i=dis.read()) !=-1) {
16
dos.write(i);
17 }} }
8-7 FileReader與FileWriter
•
• 以FileReader / FileWriter 產生之輸入/輸出串流,
可讀寫以雙位元Unicode之輸入/輸出資料,適用
亞洲各國文字之編碼,因此可用於解決中文的問
題。
範例105:設有檔案Ex08_7_1.java,其功能為解釋FileReader之應用
。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_7_1 {
03 public static void main(String args[]) throws Exception {
04
int i;
05
06
07
08
if (args.length < 1) {
System.out.println("Usage: java Ex08_7_1 [fileName]");
System.exit(1);
}
09
10
11
12
13
14 }
15 }
String fileName = args[0];
FileReader fr=new FileReader(fileName);
while((i=fr.read()) !=-1) {
System.out.print((char)i);
}
範例106:設有檔案Ex08_7_2.java,其功能為解釋FileWriter之應用
。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_7_2 {
03 public static void main(String args[]) throws Exception {
04 if (args.length < 1) {
05
System.out.println("Usage: java Ex08_7_2 [fileName]");
06
System.exit(1);
07 }
08
09
String fileName = args[0];
FileWriter fw=new FileWriter(fileName);
10
String line = "Test for FileWriter 測試FileWriter之中文";
11 fw.write(line);
12 fw.flush();
13 }
14 }
範例107:設有檔案Ex08_7_3.java,其功能為解釋以FileReader /
FileWriter將一個檔案之內容傳遞至另一個檔案內。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
class Ex08_7_3 {
public static void main(String args[]) throws Exception {
int i;
if (args.length < 2) {
System.out.println("Usage: java Ex08_7_3 [infileName] [outfileName]");
System.exit(1);
}
String infileName = args[0];
String outfileName = args[1];
FileReader fr=new FileReader(infileName);
FileWriter fw=new FileWriter(outfileName);
while((i=fr.read()) !=-1) {
fw.write(i);
}
fw.flush();
}
}
8-8鍵盤資料輸入
• 為了節省電腦的有效工作時間,我們設置緩衝器
輔助之,當使用鍵盤輸入資料時,將資料先送入
緩衝器,等到一定資料量時(按下Enter時),再將
緩衝器資料一起輸入。
範例108:設有檔案Ex08_8_1.java,其功能為解釋鍵盤資料輸入之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_8_1 {
03 public static void main(String [] args)throws IOException {
04 int i;
05
06
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
07 System.out.println("Input data in the keyboard: ");
08 while(true) {
09
i = br.read();
10
System.out.print((char)i);
11 }
12 }
13 }
範例109:設有檔案Ex08_8_2.java,其功能為解釋由鍵盤輸入資料,以
FileOutputStream串流寫入新檔案(無法寫入中文)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 mport java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class Ex08_8_2 {
public static void main(String [] args)throws IOException {
int i;
if (args.length < 1) {
System.out.println("Usage: java Ex08_8_2 [outfileName]");
System.exit(1);
}
String outfileName = args[0];
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(outfileName);
System.out.println("Input data in the keyboard: ");
while(true) {
i = br.read();
fos.write(i);
}
}
}
範例110:設有檔案Ex08_8_3.java,其功能為解釋由鍵盤輸入資料,以FileWriter
串流寫入新檔案(可寫入中文)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex08_8_3 {
03 public static void main(String [] args)throws IOException {
04 int i;
05 if (args.length < 1) {
06
System.out.println("Usage: java Ex08_8_3 [outfileName]");
07
System.exit(1);
08 }
09 String outfileName = args[0];
10 InputStreamReader isr =new InputStreamReader(System.in);
11 BufferedReader br = new BufferedReader(isr);
12 FileOutputStream fos = new FileOutputStream(outfileName);
13 FileWriter fw=new FileWriter(outfileName);
14 System.out.println("Input data in the keyboard: ");
15 while((i=br.read()) !=-1) {
16
fw.write(i);
17 }
18 fw.flush();
19 } }
第九章
執行緒(Threads)
•
•
•
•
•
•
•
•
•
•
•
9-1 簡介
9-2執行緒狀態(Thread States)
9-3 Thread類別
9-4方法程序isAlive( )、join( )
9-5方法程序suspend( )、resume( )
9-6方法程序setPriority( )、getPriority( )
9-7 synchronized之應用
9-8執行緒群組(Thread Group)之應用
9-9 習題(Exercises)
9-1 簡介
•
• 作業系統具有多工執行的功能,每一個工作系列
即為一個執行緒(Threads)。在一個時間內,CPU僅
能處理一個工作。當有多個工作同時擁入時,
CPU將其本身分割成多個工作時段,適當地分配
給各工作片斷作執行。
9-2執行緒狀態(Thread States)
•
• 當程式(Program) 被執行時,程式之任務
(Task) 演譯出一個或多個執行緒,從開始產
生(new) 到消失(terminated) 有不同的階段狀
態(States) 與流程(如圖9-2-1):
圖9-2-1
9-3 Thread類別
•
• Java系統內建Thread類別,其功能是將CPU分割成
多個工作時段,依前節所述之5個狀態,適當地提
供給條件最優的工作片斷作執行。
範例111:設有檔案Ex09_3_1.java,其功能為解釋執行緒之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例111:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21 public class Ex09_3_1 {
22 public static void main(String[] args) {
23
JOB job1 = new JOB(4,"job1");
24
JOB job2 = new JOB(4,"job2");
25
job1.start();
26
job2.start();
27 }
28 }
範例112:設有檔案Ex09_3_2.java,其功能為解釋承作Runnable與
執行緒之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB implements Runnable {
04 private String jobName;
05 private int loopLmt;
06 public JOB(int loopLmt, String jobName) {
07
this.loopLmt = loopLmt;
08
this.jobName = jobName;
09 }
10 private void PAUSE(double sec) {
11
try {Thread.sleep(Math.round(1000.0*sec));}
12
catch(InterruptedException ie) {};
13 }
範例112:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
public class Ex09_3_2 {
public static void main(String[] args) {
Thread job1 = new Thread(new JOB(4,"job1"));
Thread job2 = new Thread(new JOB(4,"job2"));
job1.start();
job2.start();
}
}
9-4方法程序isAlive( )、join( )
•
• 由類別Thread產生之新物件,其工作時機是因
CPU而機動的,故與其相關的方法程序也都與
此有關。
•
• 如9-3節,常用之方法程序有:start()、 run()、
stop()、 sleep()、 suspend()、 resume()、
setName()、 getName()、 wait()、 notify()、
join()、 isAlive()、 setPriority()、 getPriority()、
yield()。
範例113:設有檔案Ex09_4_1.java,其功能為解釋方法程序isAlive() 與join() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例113:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex09_4_1 {
public static void main(String[] args) {
JOB job1 = new JOB(4,"job1");
JOB job2 = new JOB(8,"job2");
job1.start();
job2.start();
System.out.println("job1 is alive : " +job1.isAlive());
try{job1.join();}
catch(InterruptedException ie){}
System.out.println("job1 is alive : " +job1.isAlive());
}
}
範例114:設有檔案Ex09_4_2.java,其功能為解釋承作介面Runnable與方
法程序isAlive() 、join() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB implements Runnable {
04 private String jobName;
05 private int loopLmt;
06 public JOB(int loopLmt, String jobName) {
07
this.loopLmt = loopLmt;
08
this.jobName = jobName;
09 }
10 private void PAUSE(double sec) {
11
try {Thread.sleep(Math.round(1000.0*sec));}
12
catch(InterruptedException ie) {};
13 }
範例114:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex09_4_2 {
public static void main(String[] args) {
Thread job1 = new Thread(new JOB(4,"job1"));
Thread job2 = new Thread(new JOB(8,"job2"));
job1.start();
job2.start();
System.out.println("job1 is alive : " +job1.isAlive());
try{job1.join();}
catch(InterruptedException ie){}
System.out.println("job1 is alive : " +job1.isAlive());
}
}
9-5方法程序suspend( )、resume( )
•
• 執行緒一直是處在搶先機之緊繃環境,但
也可以使用方法程序 suspend( ) 暫時退出此
緊張環境,進入等待狀態(如9-2節之Waiting
State),再視需要使用 resume( ) 伺機重新進
入就緒狀態(如9-2節之Ready State),繼續操
刀撕殺。
範例115:設有檔案Ex09_5_1.java,其功能為解釋方法程序
suspend() 與resume() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例115:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void run() {
for(int i=1; i<=loopLmt; i++) {
System.out.println(jobName + ": work" + i);
PAUSE(Math.random());
}
}
}
public class Ex09_5_1 {
public static void main(String[] args) {
JOB job1 = new JOB(4,"job1");
JOB job2 = new JOB(4,"job2");
job1.start();
job2.start();
job2.suspend();
System.out.println("job2 is suspend " );
try{job1.join();}
catch(InterruptedException ie){}
job2.resume();
System.out.println("job2 is resume");
}
}
9-7 synchronized之應用
• 眾多執行緒圍繞著CPU,拼條件隨時伺機衝入CPU
作執行,此時難免會發生錯誤,該進入的沒進入
、不該進入的反而進入,或是執行到半途被其他
執行緒趕出,又或者是因排程不當,使得多個執
行緒同時擁入CPU。
範例119:設有檔案Ex09_7_1.java,其功能為解釋使用修飾子
synchronized之應用。(模擬高鐡售票機)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class NumberIssue {
int iniNumber, numberInterval;
public NumberIssue(int iniNumber, int numberInterval) {
this.iniNumber = iniNumber;
this.numberInterval = numberInterval;
}
public synchronized int getNumber()
//public int getNumber()
{
int num= iniNumber;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {};
iniNumber= iniNumber + numberInterval;
return(num);
}
}
範例119:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
18 class Passanger extends Thread {
19 int number;
20 NumberIssue NI;
21 public Passanger(NumberIssue NI) {
22 this.NI = NI;
23 }
24 public void run() {
25 number = NI.getNumber();
26 }
27 }
28 public class Ex09_7_1 {
29 public static void main(String[] args) {
30 NumberIssue NI;
31 Passanger p1, p2, p3, p4;
範例119:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
32
NI = new NumberIssue(1,2);
33
34
35
36
p1 = new Passanger(NI);
p2 = new Passanger(NI);
p3 = new Passanger(NI);
p4 = new Passanger(NI);
37
38
39
try {
p1.join(); p2.join(); p3.join(); p4.join();
} catch (InterruptedException e) {};
p1.start();
p2.start();
p3.start();
p4.start();
40 System.out.println("Passanger 1: Number: " + p1.number);
41 System.out.println("Passanger 2: Number: " + p2.number);
42 System.out.println("Passanger 3: Number: " + p3.number);
43 System.out.println("Passanger 4: Number: " + p4.number);
44 }
45 }
範例120:設有檔案Ex09_7_2.java,其功能為解釋如果不使用修飾子synchronized
,當有多個旅客同時購票時,售票機將售出重號之車票號碼。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
class NumberIssue {
int iniNumber, numberInterval;
public NumberIssue(int iniNumber, int numberInterval) {
this.iniNumber = iniNumber;
this.numberInterval = numberInterval;
}
//public synchronized int getNumber()
public int getNumber()
{
int num= iniNumber;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {};
iniNumber= iniNumber + numberInterval;
return(num);
}
}
範例120:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
18 class Passanger extends Thread {
19 int number;
20 NumberIssue NI;
21 public Passanger(NumberIssue NI) {
22 this.NI = NI;
23 }
24 public void run() {
25 number = NI.getNumber();
26 }
27 }
28 public class Ex09_7_2 {
29 public static void main(String[] args) {
30 NumberIssue NI;
31 Passanger p1, p2, p3, p4;
範例120:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
32
NI = new NumberIssue(1,2);
33
34
35
36
p1 = new Passanger(NI);
p2 = new Passanger(NI);
p3 = new Passanger(NI);
p4 = new Passanger(NI);
37
38
39
try {
p1.join(); p2.join(); p3.join(); p4.join();
} catch (InterruptedException e) {};
p1.start();
p2.start();
p3.start();
p4.start();
40 System.out.println("Passanger 1: Number: " + p1.number);
41 System.out.println("Passanger 2: Number: " + p2.number);
42 System.out.println("Passanger 3: Number: " + p3.number);
43 System.out.println("Passanger 4: Number: " + p4.number);
44 }
45 }
9-8執行緒群組(Thread Group)之應用
•
• 為了便於管理,我們可將某些執行緒依需
要歸納成群組,如此編組是謂 “執行緒群組
”。
•
• Java系統有內建執行緒群組類別
ThreadGroup,由ThreadGroup產生群組新物
件,如此產生的新物件具有容納多個子執
行緒(Sub Thread) 的功能。
範例121:設有檔案Ex09_8.java,其功能為解釋執行緒群組之應用
。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class JOB extends Thread {
03 int sum;
04 boolean running = true;
05 JOB (ThreadGroup grp, String threadName, int initValue) {
06
super(grp, threadName);
07
this.sum = initValue;
08 }
09 public void run() {
10
while(running)
11
sum = sum + 1;
12 }
13 }
範例121:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public class Ex09_8 {
15 public static void main(String[] args) {
16
ThreadGroup grp1 = new ThreadGroup("grp1");
17
ThreadGroup grp2 = new ThreadGroup("grp2");
18
19
20
21
JOB a1 = new JOB(grp1, "a1", 0);
JOB a2 = new JOB(grp1, "a2", 0);
JOB a3 = new JOB(grp2, "a3", 0);
JOB a4 = new JOB(grp2, "a4", 0);
22
23
24
25
a1.start();
a2.start();
a3.start();
a4.start();
26
27
try {Thread.sleep(1000);}
catch(InterruptedException e){}
範例121:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
28
29
grp1.stop();
grp2.stop();
30
31
32
33
34
35
try {
a1.join();
a2.join();
a3.join();
a4.join();
} catch (InterruptedException e) {};
36
37
38
39
40 }
41 }
System.out.println("grp1_a1: sum = "+a1.sum);
System.out.println("grp1_a2: sum = "+a2.sum);
System.out.println("grp2_a3: sum = "+a3.sum);
System.out.println("grp2_a4: sum = "+a4.sum);
第二篇
網路串流(Data Stream in Network)
第十章
網路結構概念(Network Structure Concepts)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
10-1 簡介
10-2 網路意義(Background)
10-2-1 網路系統之優點(Advantages of Network Systems)
10-2-2作業系統之類型(Types of Operating System)
10-3 節點連接(Topology)
10-4 網路通訊(Communication)
10-4-1 名稱解析(Naming Resolution)
10-4-2 路由策略(Routing Strategies)
10-4-3 連接策略(Connection Strategies)
10-4-4 衝突避免(Contention)
10-5 網路通訊協定(Communication Protocols)
10-6 網路故障處理(Robustness)
10-7 習題(Exercises)
10-1 簡介
•
• 網路系統 (Network System) 是多個處理器
(Processors) 的組合,各處理器散置於各不同地區
,彼此間互不共享記憶體,各有其自己的記憶體
(Memory),以地區網路(LAN Local Area Network)
或廣域網路(WAN Wide Area Network) 互通訊息。
本章將探討網路系統結構之概念。
10-2 網路意義(Background)
•
• 網路系統(Network System) 是多個電腦處理
器(Processors) 的組合,從小型的手持微電
腦、個人電腦、到大型的工作站,散置於
各不同地區(Sites),由網路互相連通、互相
支援。
10-3 節點連接(Topology)
•
• 網路系統是將散置於各處的處理器(Processors) 以
網路連接,互通訊息。其中有許多連接方式,各
有其優缺點
10-4 網路通訊(Communication)
•
• 當探討網路通訊,我們須考量:(1) 名稱解析
(Naming Resolution),各節點之行程(Processes) 如
何在廣大的網域中互相定址對方? (2) 路由策略
(Routing Strategies),如何在網域中選擇傳遞資料
之途徑? (3) 連接策略(Connection Strategies),網
路中如何安排多個行程同時傳遞資料? (4) 衝突避
免(Contention),當發生網路上爭議的問題時,如
何解決?
10-5 網路通訊協定
(Communication Protocols)
•
• 網路上電腦節點眾多且資料格式不盡相同,強迫
互相傳遞資料,將無法順利執行。我們必須設定
一個各節點都可接受的協定(Protocol),讓所有節
點都依協定的要求遂行資料傳遞,如此才可順利
執行。
10-6 網路故障處理(Robustness)
•
• 網路節點眾多,發生故障的機會更是稀鬆平常,如
連線故障(Failure of Link)、電腦節點故障(Failure of
Site)、資料遺失(Loss of Message) 等。
•
• 為了維護網路隨時保持良好狀態,網路應有能力執
行:偵測故障(Detect Failure)、重組系統
(Reconfiguration)、與修補故障(Recovery from
Failure)。
第十一章
網路連接(Server/Client Connection)
•
•
•
•
•
•
•
•
•
11-1 簡介
11-2 ServerSocket Class
11-3 InetAddress Class
11-4 Socket Class
11-5 指令參數與Server/Client連接
11-6 多次Server/Client連接記錄
11-7 習題(Exercises)
11-1 簡介
•
• 本章將以Server / Client端點介紹如何作網路連接。
設計Server端網路程式,等待被Client端連接;設計
Client端網路程式,連接Server端。Server端以設定
之執行埠(port) 建置伺服平台(ServerSocket),當
Client端有訊息來連接時,以連接平台(Socket)之接
收功能接受連接,並捉取Client端的網址(IP) 印出之
。Client端以Server之網址(IP)、及設定之執行埠
(port) 建立網路連接平台,由Client端連接Server端
。
11-2 ServerSocket Class
•
• java.net.ServerSocket繼承自Object,此類別產生的新
物件,可依本機之網址(IP)、與設定之執行埠(port)
建立Server端網站平台(ServerSocket),等待Client端
來連接。其中執行埠(port) 不得設定已被使用者(參
考附錄D),否則將無法成功建立。
範例122:設有檔案Server11_2.java,其功能為解釋如何建立
ServerSocket網路平台?
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
import java.net.*;
import java.io.*;
class Server11_2 {
public static void main(String args[]) {
try {
ServerSocket SS1 = new ServerSocket(1234);
System.out.println("ServerSocket SS1 is created");
System.out.println("SS1.getLocalPort() = " + SS1.getLocalPort());
SS1.close();
System.out.println(“SS1 is closed”);
ServerSocket SS2 = new ServerSocket(0, 2);
System.out.println("ServerSocket SS2 is created");
System.out.println("SS2.getLocalPort() = " + SS2.getLocalPort());
SS2.close();
System.out.println("SS1 is closed");
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
11-3 InetAddress Class
•
• java.net.InetAddress繼承自Object,此類別
產生的新物件,可依指定電腦之名稱或IP,
建立一個網路位置,使用在封包(Datagram
Packet) 或網路平台(Socket) 之類別內。此類
別無建構子,故不得用於執行繼承。
範例123:設有檔案Server11_3.java,其功能為解釋類別
InetAddress之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 class Server11_3 {
04 public static void main(String args[]) {
05 try {
06
InetAddress iaddr = InetAddress.getByName("163.15.40.242");
07
System.out.println("iaddr.getHostAddress() = " + iaddr.getHostAddress());
08
System.out.println("iaddr.getHostName() = " + iaddr.getHostName());
09 }
10 catch(UnknownHostException e) {
11
System.out.println(e.getMessage());
12 }
13 }
14 }
11-4 Socket Class
•
• java.net.Socket繼承自Object,此類別產生的
新物件,可依網站之IP和port,與Server網
站連接,進而以網路串流執行遠端讀取或
寫入。
範例124:設有檔案Server11_4_1.java、Client11_4_1.java其功能為
解釋Server/Client如何執行網路連接?
•
•
•
•
•
•
•
•
檔案Server11_4_1.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server11_4_1 {
04 public Server11_4_1() {
05 try{
06
ServerSocket SS = new ServerSocket(1234);
07
System.out.println(“Server is created and waiting Client to connect...”);
•
•
•
•
•
•
•
•
•
•
•
•
08
09
10
11
12
13
14
15
16
17
18
19
Socket socket = SS.accept();
System.out.println(“connected from Client ” + socket.getInetAddress());
socket.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
Server11_4_1 ServerStart=new Server11_4_1();
}
}
檔案Client11_4_1.java:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
20 import java.io.*;
21 import java.net.*;
22 public class Client11_4_1 {
23 public Client11_4_1() {
24 try{
25
Socket socket = new Socket("163.15.40.242", 1234);
26
socket.close();
27 }
28 catch(IOException e){
29
System.out.println(e.getMessage());
30 }
31 }
32 public static void main(String args[]) {
33 Client11_4_1 ClientStart=new Client11_4_1();
34 }
35 }
範例125:設有檔案Server11_4_2.java、Client11_4_2.java其功能為解釋Server/Client連接、
類別InetAddress、方法程序getLocalPort()、getPort() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server11_4_2.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server11_4_2 {
04 public Server11_4_2() {
05 try{
06
ServerSocket SS = new ServerSocket(1234);
07
System.out.println("Server is created and waiting Client to connect...");
08
Socket socket = SS.accept();
09
System.out.println("connected from Client " + socket.getInetAddress());
10
System.out.println("Server Local Port = " + socket.getLocalPort());
11
System.out.println("Client Port = " + socket.getPort());
12
socket.close();
13 }
14 catch(IOException e){
15
System.out.println(e.getMessage());
16 }
17 }
18 public static void main(String args[]){
19
Server11_4_2 ServerStart=new Server11_4_2();
20 }
21 }
檔案Client11_4_2.java:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
22 import java.io.*;
23 import java.net.*;
24 public class Client11_4_2 {
25 public Client11_4_2() {
26 try{
27
InetAddress iaddr = InetAddress.getByName("163.15.40.242");
28
Socket socket = new Socket(iaddr, 1234);
29
System.out.println("Client Local Port = " + socket.getLocalPort());
30
System.out.println("Server Port = " + socket.getPort());
31
socket.close();
32 }
33 catch(IOException e){
34
System.out.println(e.getMessage());
35 }
36 }
11-5 指令參數與Server/Client連接
•
• 於前節、IP與port為程式之固定設定值,一旦完成
編譯即無法改變,極不方便使用。如8-2節、如果改
以指令參數(Command Parameters) 設定IP與port,我
們即可將完成之編譯碼,使用於任何Server/Client之
連接,方便又機動,這也是正式應用之設計方式。
範例126:設有檔案Server11_5.java、Client11_5.java其功能為解釋
Server/Client連接、與指令參數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server11_5.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server11_5 {
04 static int port;
05 public Server11_5() {
06 try{
07
ServerSocket SS = new ServerSocket(port);
08
System.out.println("Server is created and waiting Client to connect...");
09
10
11
12
Socket socket = SS.accept();
System.out.println("connected from Client " +
socket.getInetAddress().getHostAddress());
socket.close();
}
檔案Server11_5.java:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
13 catch(IOException e){
14
System.out.println(e.getMessage());
15 }
16 }
17 public static void main(String args[]){
18 if(args.length < 1){
19
System.out.println("Usage: java Server11_5 [port]");
20
System.exit(1);
21 }
22 port=Integer.parseInt(args[0]);
23 Server11_5 ServerStart=new Server11_5();
24 }
25 }
檔案Client11_5.java:
•
•
•
•
•
•
•
•
•
•
26 import java.io.*;
27 import java.net.*;
28 public class Client11_5 {
29 static String iaddr;
30 static int port;
31 public Client11_5() {
32 try{
33
Socket socket=new
Socket(InetAddress.getByName(iaddr),port);
• 34
socket.close();
• 35 }
檔案Client11_5.java:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
36 catch(IOException e){
37
System.out.println(e.getMessage());
38 }
39 }
40 public static void main(String args[]) {
41 if (args.length < 2){
42
System.out.println("USAGE: java Client11_5 [iaddr] [port]");
43
System.exit(1);
44 }
45 iaddr = args[0];
46 port =Integer.parseInt(args[1]);
47 Client11_5 ClientStart=new Client11_5();
48 }
49 }
11-6 多次Server/Client連接記錄
•
• 於前節、當Server網站建立後,僅允許被Client端連
接一次。本節將修改前節程式,允許Server網站被
多個Client端作多次連接,並記錄各Client端之IP、
port、與時間。
範例127:設有檔案Server11_6.java、Client11_6.java其功能為解釋如何執行Server網站被多
個Client端作多次連接,並記錄各Client端之IP、port、與時間。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server11_6.java:
01 import java.net.*;
02 import java.io.*;
03 import java.util.*;
04 public class Server11_6 {
05 static int port;
06 public Server11_6() {
07 try{
08
ServerSocket SS = new ServerSocket(port);
09
System.out.println("Server is created and waiting Client to connect...");
10
11
12
13
14
15
16
17
18
while(true){
Socket socket = SS.accept();
Date currentDate = new Date();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
System.out.println("Client port = " + socket.getPort());
System.out.println("Connect date = " + currentDate);
System.out.println("waiting...");
}
}
檔案Server11_6.java:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
19 catch(IOException e){
20
System.out.println(e.getMessage());
21 }
22 }
23 public static void main(String args[]){
24
if(args.length < 1){
25
System.out.println("Usage: java Server11_6 [port]");
26
System.exit(1);
27
}
28
port=Integer.parseInt(args[0]);
29
Server11_6 ServerStart=new Server11_6();
30 }
31 }
檔案Client11_6.java:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
32 import java.io.*;
33 import java.net.*;
34 public class Client11_6 {
35 static String iaddr;
36 static int port;
37 public Client11_6() {
38 try{
39
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
40
System.out.println("To connect Server");
41
socket.close();
42 }
43 catch(IOException e){
44
System.out.println(e.getMessage());
45 }
46 }
檔案Client11_6.java:續
•
•
•
•
•
•
•
•
•
•
47 public static void main(String args[]) {
48 if (args.length < 2){
49
System.out.println("USAGE: java Client11_6 [iaddr] [port]");
50
System.exit(1);
51 }
52 iaddr = args[0];
53 port = Integer.parseInt(args[1]);
54 Client11_6 ClientStart=new Client11_6();
55 }
56 }
第十二章
網路訊息傳遞(Message Transition)
•
•
•
•
•
•
12-1 簡介
12-2 DataInputStream Class
12-3 DataOutputStream Class
12-4訊息傳遞(Network Message Translation)
12-5 習題(Exercises)
12-1 簡介
•
• 當Server端與Client端連接後,彼此以網路串
流將資料相互傳遞。本章介紹如何於Client
端以指令參數輸入訊息,交由網路輸出串
流物件,傳送至Server端印出,再讀取
Server端指令參數訊息,回傳至Client端印出
,完成訊息相互傳遞。
12-2 DataInputStream Class
•
• java.io.DataInptStream繼承(extends)自
FilterInputStream→InputStream→Object,承作
(implements)自DataInput。此類別為串流物件,可
用於讀取網路平台之輸入串流。
12-3 DataOutputStream Class
•
• java.io.DataOutptStream繼承(extends)自
FilterOutputStream→ OutputStream→ Object,承作
(implements)自DataOutput。此類別為串流物件,
可用於讀取網路平台之輸出串流。
12-4訊息傳遞(Message Translation)
• 設計範例128,於Client端、以指令參數鍵入訊息
(Message),由網路將訊息傳送到Server端印出。
範例128:設有檔案Server12_4_1.java、Client12_4_1.java其功能為
解釋將Client端指令參數訊息傳送到Server端印出。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server12_4_1.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server12_4_1 {
04 static int port;
05 public Server12_4_1() {
06 try{
07 ServerSocket SS = new ServerSocket(port);
08 System.out.println("Server is created and waiting Client to connect...");
09
10
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
範例128:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
11 DataInputStream instream = new
DataInputStream(socket.getInputStream());
12 String messagein = instream.readUTF();
13 System.out.println("messagein = " + messagein);
14 }
15 catch(IOException e){
16 System.out.println(e.getMessage());
17 }
18 }
19 public static void main(String args[]){
20 if(args.length < 1){
21 System.out.println("Usage: java Server12_4_1 [port]");
22 System.exit(1);
23 }
24 port=Integer.parseInt(args[0]);
25 Server12_4_1 ServerStart=new Server12_4_1();
26 }
27 }
範例128:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client12_4_1.java:
28 import java.io.*;
29 import java.net.*;
30 public class Client12_4_1 {
31 static String iaddr;
32 static int port;
33 static String messageout;
34 public Client12_4_1() {
35 try{
36 Socket socket=new Socket(InetAddress.getByName(iaddr),port);
37 DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
38 outstream.writeUTF(messageout);
39
System.out.println("Message is transferred to Server");
40
socket.close();
範例128:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
41 }
42 catch(IOException e){
43 System.out.println(e.getMessage());
44 }
45 }
46 public static void main(String args[]) {
47 if (args.length < 3){
48 System.out.println("USAGE: java Client12_4_1 [iaddr] [port] [messageout]");
49 System.exit(1);
50 }
51 iaddr = args[0];
52 port=Integer.parseInt(args[1]);
53 messageout = args[2];
54 Client12_4_1 ClientStart=new Client12_4_1();
55 }
56 }
範例129:設有檔案Server12_4_2.java、Client12_4_2.java其功能為
解釋多個Client端對Server連接,並相互傳遞訊息印出。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server12_4_2.java:
01 import java.net.*;
02 import java.io.*;
03 import java.util.*;
04 public class Server12_4_2 {
05 static int port;
06 static String messageout;
07 static String messagein;
08 public Server12_4_2() {
09 try{
10 ServerSocket SS = new ServerSocket(port);
11 System.out.println("Server is created and waiting Client to connect...");
12
Date currentDate = new Date();
13
14
15
while(true){
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
範例129:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
16
System.out.println("date = " + currentDate);
17
DataInputStream instream = new
DataInputStream(socket.getInputStream());
18
messagein = instream.readUTF();
19
System.out.println("messagein = " + messagein);
20
System.out.println("waiting...");
21
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
22
outstream.writeUTF(messageout);
23
24
25
26
27
28 }
}
}
catch(IOException e){
System.out.println(e.getMessage());
}
範例129:續2
• 29 public static void main(String args[]){
• 30 if(args.length < 2){
• 31
System.out.println("Usage: java Server12_4_2 [port]
[messageout]");
• 32
System.exit(1);
• 33 }
• 34 port=Integer.parseInt(args[0]);
• 35 messageout = args[1];
• 36 Server12_4_2 ServerStart=new Server12_4_2();
• 37 }
• 38 }
範例129:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client12_4_2.java:
39 import java.io.*;
40 import java.net.*;
41 public class Client12_4_2 {
42 static String messageout;
43 static String iaddr;
44 static int port;
45 public Client12_4_2() {
46 try{
47 Socket socket = new Socket(InetAddress.getByName(iaddr), port);
48 DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
49 outstream.writeUTF(messageout);
範例129:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
50 DataInputStream instream=new
DataInputStream(socket.getInputStream());
51 String messagein = instream.readUTF();
52 System.out.println("messagein = " + messagein);
53 socket.close();
54 }
55 catch(IOException e){
56 System.out.println(e.getMessage());
57 }
58 }
範例129:續5
• 59 public static void main(String args[]) {
• 60 if (args.length < 3){
• 61 System.out.println("USAGE: java Client12_4_2 [iaddr] [port]
[messageout]");
• 62 System.exit(1);
• 63 }
•
• 64 iaddr = args[0];
• 65 port=Integer.parseInt(args[1]);
• 66 messageout = args[2];
• 67 Client12_4_2 ClientStart=new Client12_4_2();
• 68 }
• 69 }
第十三章
網路檔案傳遞(File Transition)
•
•
•
•
•
•
•
•
•
13-1 簡介
13-2 FileInputStream Class
13-3 FileOutputStream Class
13-4 檔案傳遞(File Translation)
13-5 檔案上傳(File Upload)
13-6 檔案下載(File Download)
13-7 習題(Exercises)
13-1 簡介
•
• 前章網路訊息傳遞,是為小宗串流傳遞,本章將
介紹網路檔案傳遞,是為大宗串流傳遞。除了要
使用網路資料串流外,另外要使用本機當地資料
串流,讀取檔案內的資料、或將資料寫入檔案。
13-2 FileInputStream Class
•
• java.io.FileInputStream繼承(extends) 自
InputStream→Object,此類別從檔案建立一個低階
輸入串流,使用其中之方法程序讀取檔案內容。
13-3 FileOutputStream Class
• java.io.FileOutputStream繼承(extends) 自
OutputStream→Object,此類別建立一個低階輸出
串流,使用其中之方法程序將串流內容寫入指定
檔案。
13-4 檔案傳遞(File Translation)
•
• 設計範例130,於Client端讀取特定檔案的內容,
再由網路將內容傳送到Server端之特定檔案內。
範例130:設有檔案Server13_4.java、Client13_4.java其功能為解釋
檔案傳遞之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server13_4.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server13_4 {
04 int messagein;
05 static int port;
06 static String outfilename;
07 public Server13_4() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server is created and waiting Client to connect...");
11
12
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
範例130:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
13
DataInputStream instream = new
DataInputStream(socket.getInputStream());
14
FileOutputStream fos = new FileOutputStream(outfilename);
15
16
17
18
19
20
21
22
23
24
while(messagein != -1){
messagein = instream.readInt();
fos.write(messagein);
}
System.out.println("Data written to File successfully!");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
範例130:續2
•
•
•
•
•
•
•
•
•
•
25 public static void main(String args[]){
26 if(args.length < 2){
27 System.out.println("Usage: java Server13_4 [port] [outfilename]");
28 System.exit(1);
29 }
30 port=Integer.parseInt(args[0]);
31 outfilename = args[1];
32 Server13_4 ServerStart=new Server13_4();
33 }
34 }
範例130:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client13_4.java:
35 import java.io.*;
36 import java.net.*;
37 public class Client13_4 {
38 int i;
39 static String iaddr;
40 static int port;
41 static String infilename;
42 public Client13_4() {
43 try{
44
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
45
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
46
FileInputStream fis = new FileInputStream(infilename);
範例130:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
47
while((i=fis.read()) !=-1)
outstream.writeInt(i);
outstream.writeInt(i);
48
49
50
51
System.out.println("Data sent to internet successfully!");
socket.close();
}
52 catch(IOException e){
53
System.out.println(e.getMessage());
54 }
55 }
範例130:續5
• 56 public static void main(String args[]) {
• 57 if (args.length < 3){
• 58 System.out.println("USAGE: java Client13_4 [iaddr] [port]
[infilename]");
• 59 System.exit(1);
• 60 }
•
• 61 iaddr = args[0];
• 62 port=Integer.parseInt(args[1]);
• 63 infilename = args[2];
• 64 Client13_4 ClientStart=new Client13_4();
• 65 }
• 66 }
13-5 檔案上傳(File Upload)
•
• 設計範例131,從Client端將特定檔案由網路上傳
(Upload) 到Server端所在目錄內。也即、當要對特
定檔案執行網路上傅時,將本例Client.class置於該
特定檔案所在目錄,再將本例Server.class置於遠
端目的目錄,依執行步驟即可上傳該特定檔案。
範例131:設有檔案Server_upload.java、Client_upload.java其功能為
解釋檔案上傳之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server_upload.java:
01 import java.net.*;
02 import java.io.*;
03 public classServer_upload {
04 static int port;
05 static String uploadFile;
06 int messagein;
07 public Server_upload() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server_upload is ready...");
11
12
Socket cmdsocket = SS.accept();
Socket datasocket = SS.accept();
範例131:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
13
System.out.println("Client IP = " +
cmdsocket.getInetAddress().getHostAddress());
14
DataInputStream cmdinstream = new
DataInputStream(cmdsocket.getInputStream());
15
uploadFile = cmdinstream.readUTF();
16
DataInputStream datainstream = new
DataInputStream(datasocket.getInputStream());
17
FileOutputStream fos = new FileOutputStream(uploadFile);
18
while(messagein != -1){
19
messagein = datainstream.readInt();
20
fos.write(messagein);
21
}
22
System.out.println("File is uploaded successfully!");
23 }
範例131:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
24 catch(IOException e){
25
System.out.println(e.getMessage());
26 }
27 }
28 public static void main(String args[]){
29 if(args.length < 1){
30 System.out.println("Usage: java Server_upload [port]");
31 System.exit(1);
32 }
33 port = Integer.parseInt(args[0]);
34 Server_upload ServerStart=new Server_upload();
35 }
36 }
範例131:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client_upload.java:
37 import java.io.*;
38 import java.net.*;
39 public class Client_upload {
40 int i;
41 static String iaddr;
42 static int port;
43 static String uploadFile;
44 public Client_upload() {
45 try{
46
Socket cmdsocket=new Socket(InetAddress.getByName(iaddr),port);
47
Socket datasocket=new Socket(InetAddress.getByName(iaddr),port);
範例131:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
48
DataOutputStream cmdoutstream = new
DataOutputStream(cmdsocket.getOutputStream());
49
cmdoutstream.writeUTF(uploadFile);
50
DataOutputStream dataoutstream = new
DataOutputStream(datasocket.getOutputStream());
51
FileInputStream fis = new FileInputStream(uploadFile);
52
while((i=fis.read()) !=-1)
dataoutstream.writeInt(i);
53
dataoutstream.writeInt(i);
54
55
56
57
System.out.println("File is sent to internet successfully!");
cmdsocket.close();
datasocket.close();
}
範例131:續5
•
•
•
•
•
•
•
•
58 catch(IOException e){
59
System.out.println(e.getMessage());
60 }
61 }
•
•
•
•
•
•
•
•
•
65 System.exit(1);
66 }
62 public static void main(String args[]) {
63 if (args.length < 3){
64 System.out.println("USAGE: java Client_upload [iaddr] [port] [uploadFile]");
67 iaddr = args[0];
68 port=Integer.parseInt(args[1]);
69 uploadFile = args[2];
70 Client_upload ClientStart=new Client_upload();
71 }
72 }
13-6 檔案下載(File Download)
•
• 設計範例132,從Client端對Server端所在目
錄內之檔案執行下載(Download)。也即、當
要對特定檔案執行網路下載時,將本例
Client.class置於需求目錄內,再將本例
Server.class置於遠端檔案群目錄內,依執行
步驟從Client端對Server端目錄內之特定檔案
執行下載。
範例132:設有檔案Server_download.java、Client_download.java其
功能為解釋檔案下載之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server_download.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server_download {
04 static int port;
05 static String downloadFile;
06 int messagein, i;
07 public Server_download() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server_download is ready...");
範例132:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
11
12
Socket cmdsocket = SS.accept();
Socket datasocket = SS.accept();
13
System.out.println("Client IP = " +
cmdsocket.getInetAddress().getHostAddress());
14
DataInputStream cmdinstream = new
DataInputStream(cmdsocket.getInputStream());
15
downloadFile = cmdinstream.readUTF();
16
DataOutputStream dataoutstream = new
DataOutputStream(datasocket.getOutputStream());
17
FileInputStream fis = new FileInputStream(downloadFile);
18
while((i=fis.read()) !=-1)
19
dataoutstream.writeInt(i);
20
dataoutstream.writeInt(i);
範例132:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
21
22
23
24
25
26
27
28 }
System.out.println("File is sent to internet successfully!");
datasocket.close();
cmdsocket.close();
}
catch(IOException e){
System.out.println(e.getMessage());
}
29 public static void main(String args[]){
30 if(args.length < 1){
31 System.out.println("Usage: java Server_download [port]");
32
System.exit(1);
33 }
34 port=Integer.parseInt(args[0]);
35 Server_download ServerStart=new Server_download();
36 }
37 }
範例132:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client_download.java:
38 import java.io.*;
39 import java.net.*;
40 public class Client_download {
41 int i;
42 static String iaddr;
43 static int port;
44 static String downloadFile;
45 int messagein;
46 public Client_download() {
47 try{
48
Socket cmdsocket=new Socket(InetAddress.getByName(iaddr),port);
49
Socket datasocket=new Socket(InetAddress.getByName(iaddr),port);
範例132:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
50
DataOutputStream cmdoutstream = new
DataOutputStream(cmdsocket.getOutputStream());
51
cmdoutstream.writeUTF(downloadFile);
52
DataInputStream datainstream = new
DataInputStream(datasocket.getInputStream());
53
FileOutputStream fos = new FileOutputStream(downloadFile);
54
55
56
57
58
59
60
61
while(messagein != -1){
messagein = datainstream.readInt();
fos.write(messagein);
}
System.out.println("File is downloaded successfully!");
cmdsocket.close();
datasocket.close();
}
範例132:續5
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
62 catch(IOException e){
63
System.out.println(e.getMessage());
64 }
65 }
66 public static void main(String args[]) {
67 if (args.length < 3){
68 System.out.println("USAGE: java Client_download [iaddr] [port]
[downloadFile]");
69 System.exit(1);
70 }
71 iaddr = args[0];
72 port=Integer.parseInt(args[1]);
73 downloadFile = args[2];
74 Client_download ClientStart=new Client_download();
75 }
76 }
第十四章
網路鍵盤輸入(Input from Key)
•
•
•
•
•
•
•
•
14-1 簡介
14-2 BufferedInputStream Class
14-3 BufferedOutputStream Class
14-4 鍵盤輸入/遠端印出
14-5 鍵盤輸入/遠端檔案
14-6 習題(Exercises)
14-1 簡介
•
• 本章內容為Server / Client鍵盤輸入資料傳遞。於
Client端、建立鍵盤輸入物件,讀取鍵盤輸入資料
,再以網路輸出串流物件、將資料從網路傳送至
Server端。Server端建立網路輸入串流物件,讀取
網路傳來的資料。
14-2 BufferedInputStream Class
•
• java.io.BufferedInputStream繼承(extends) 自
InputStream→Object,此類別將已存在之串流
資料聚集於緩衝器內,當聚集一定數量後再執
行一次輸入,如此可節省輸入次數之浪費,按
下Enter鍵執行一次輸入。此類別的缺點是無法
傳遞中文。
14-3 BufferedOutputStream Class
•
• java.io.BufferedOutputStream繼承(extends)
自OutputStream→Object,此類別將已存在
之串流資料聚集於緩衝器內,當聚集一定
數量後再執行一次輸出,如此可節省輸出
次數之浪費,按Enter鍵執行一次輸出。
14-4 鍵盤輸入/遠端印出
•
• 設計範例133,於Client端由鍵盤輸入資料,
由網路傳遞至Server端印出。因是鍵盤輸入
,應考量緩衝器之使用。
範例133:設有檔案Server14_4_1.java、Client14_4_1.java其功能為
解釋鍵盤輸入與遠端印出之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server14_4_1.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server14_4_1 {
04 Socket socket;
05 static int port;
06 int messagein;
07 public Server14_4_1() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server is created and waiting Client to connect...");
範例133:續1
•
•
•
•
•
•
•
•
•
•
•
11
12
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
13
DataInputStream instream = new
DataInputStream(socket.getInputStream());
14
15
16
17
18
while(true) {
messagein = instream.readInt();
System.out.print((char)messagein);
}
}
範例133:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
19 catch(IOException e){
20
System.out.println(e.getMessage());
21 }
22 }
23 public static void main(String args[]){
24 if(args.length < 1){
25
System.out.println("Usage: java Server14_4_1 [port]");
26
System.exit(1);
27 }
28 port=Integer.parseInt(args[0]);
29 Server14_4_1 ServerStart=new Server14_4_1();
30 }
31 }
範例133:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client14_4_1.java:
32 import java.io.*;
33 import java.net.*;
34 public class Client14_4_1 {
35 int i;
36 static String iaddr;
37 static int port;
38 public Client14_4_1() {
39 try{
40
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
41
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
範例133:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
42
43
BufferedInputStream bis = new BufferedInputStream(System.in);
System.out.println("Input data on keyboard...");
44
45
46
47
48
while(true) {
i = bis.read();
outstream.writeInt(i);
}
}
49 catch(IOException e){
50
System.out.println(e.getMessage());
51 }
52 }
範例133:續5
•
•
•
•
•
•
•
•
•
•
•
53 public static void main(String args[]) {
54 if (args.length < 2){
55
System.out.println("USAGE: java Client14_4_1 [iaddr] [port]");
56
System.exit(1);
57 }
58 iaddr= args[0];
59 port=Integer.parseInt(args[1]);
60 Client14_4_1 ClientStart=new Client14_4_1();
61 }
62 }
範例134:設有檔案Server14_4_2.java、Client14_4_2.java其功能為
解釋改進範例133執行中文傳遞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server14_4_2.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server14_4_2 {
04 Socket socket;
05 static int port;
06 int messagein;
07 public Server14_4_2() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server is created and waiting Client to connect...");
11
12
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
13
DataInputStream instream = new
DataInputStream(socket.getInputStream());
範例134:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
15
16
17
18
19
20
21
22
while(true) {
messagein = instream.readInt();
System.out.print((char)messagein);
}
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
23 public static void main(String args[]){
24 if(args.length < 1){
25
System.out.println("Usage: java Server14_4_2 [port]");
26
System.exit(1);
27 }
28 port=Integer.parseInt(args[0]);
29 Server14_4_2 ServerStart=new Server14_4_2();
30 }
31 }
範例134:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client14_4_2.java:
32 import java.io.*;
33 import java.net.*;
34 public class Client14_4_2 {
35 int i;
36 static String iaddr;
37 static int port;
38 public Client14_4_2() {
39 try{
40
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
41
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
42
43
44
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Input data on keyboard...");
範例134:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
45
while(true) {
46
i = br.read();
47
outstream.writeInt(i);
48
}
49 }
50 catch(IOException e){
51
System.out.println(e.getMessage());
52 }
53 }
54 public static void main(String args[]) {
55 if (args.length < 2){
56
System.out.println("USAGE: java Client14_4_2 [iaddr] [port]");
57
System.exit(1);
58 }
59 iaddr= args[0];
60 port=Integer.parseInt(args[1]);
61 Client14_4_2 ClientStart=new Client14_4_2();
62 }
63 }
14-5 鍵盤輸入/遠端檔案
• 設計範例135,於Client端由鍵盤輸入資料,
由網路傳遞至Server端之指定檔案。因使用
InputStreamReader()、BufferedReader() 讀取
鍵盤輸入, 使用FileWriter() 寫入檔案,故
可執行中文傳遞。
範例135:設有檔案Server14_5.java、Client14_5.java其功能為解釋
鍵盤輸入與遠端檔案之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server14_5.java:
01 import java.net.*;
02 import java.io.*;
03 public class Server14_5 {
04 static int port;
05 static String outfilename;
06 int messagein;
07 public Server14_5() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server is created and waiting Client to connect...");
11
12
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
範例135:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
13
DataInputStream instream = new
DataInputStream(socket.getInputStream());
14
FileWriter fw = new FileWriter(outfilename);
15
16
17
18
19
20
21
22
23
24
25
while(messagein != -1){
messagein = instream.readInt();
fw.write(messagein);
}
fw.flush();
System.out.println("Data written to File successfully!");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
範例135:續2
• 26 public static void main(String args[]){
• 27 if(args.length < 2){
• 28 System.out.println("Usage: java Server14_5
[port] [outfilename]");
• 29 System.exit(1);
• 30 }
• 31 port=Integer.parseInt(args[0]);
• 32 outfilename = args[1];
• 33 Server14_5 ServerStart=new Server14_5();
• 34 }
• 35 }
範例135:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client14_5.java:
36 import java.io.*;
37 import java.net.*;
38 public class Client14_5 {
39 int i;
40 static String iaddr;
41 static int port;
42 public Client14_5() {
43 try{
44
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
45
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
範例135:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
46
47
48
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Input data on keyboard...");
49
while(true) {
50
i = br.read();
51
outstream.writeInt(i);
52
}
53 }
54 catch(IOException e){
55
System.out.println(e.getMessage());
56 }
57 }
範例135:續5
• 58 public static void main(String args[]) {
• 59 if (args.length < 2){
• 60
System.out.println("USAGE: java Client14_5 [iaddr]
[port]");
• 61
System.exit(1);
• 62 }
•
• 63 iaddr = args[0];
• 64 port=Integer.parseInt(args[1]);
• 65 Client14_5 ClientStart=new Client14_5();
• 66 }
• 67 }
第十五章
網路對播(Intercross Transition)
•
• 15-1 簡介
• 15-2 鍵盤輸入 / 對播印出
• 15-3 習題(Exercises)
15-1 簡介
•
• 前述各章節均在描述Client端發射訊息、Server端
接收訊息。本章將探討Server/Client相互發射與接
收之網路對播(Intercross Transition),其中關鍵問
題在當一個節點於發射信文時,無法同時接收信
文。
15-2 鍵盤輸入 / 對播印出
•
• Server/Client相互發射與接收之關鍵問題,在於發
射時無法同時執行接收。於本章、使用特殊符號
,將發射與接收時段以人工方式分隔;將再於第
二十章探討如何以系統功能執行自動分隔。
範例136:設有檔案Server15.java、Client15.java其功能為解釋
Server/Client網路對播之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server15.java:
01 import java.net.*;
02 import java.io.*;
03 import java.util.*;
04 public class Server15 {
05 static int port;
06 int messagein, flag, i;
07 public Server15() {
08 try{
09
ServerSocket SS = new ServerSocket(port);
10
System.out.println("Server is created and waiting Client to connect...");
範例136:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
11
12
Socket socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
13
DataInputStream instream = new
DataInputStream(socket.getInputStream());
14
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
15
16
17
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Input data on keyboard...");
18
while(true) {
範例136:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
19
20
21
22
23
24
messagein = instream.readInt();
System.out.print((char)messagein);
if (messagein == 64) {
flag = 1;
System.out.println(" ");
}
25
26
27
28
29
30
31
32
33
while(flag == 1) {
i = br.read();
outstream.writeInt(i);
if (i == 64) {
flag = 0;
}
}
}
}
範例136:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
34 catch(IOException e){
35
System.out.println(e.getMessage());
36 }
37 }
38 public static void main(String args[]){
39 if(args.length < 1){
40
System.out.println("Usage: java Server15 [port]");
41
System.exit(1);
42 }
43 port=Integer.parseInt(args[0]);
44 Server15 ServerStart=new Server15();
45 }
46 }
範例136:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client15.java:
47 import java.io.*;
48 import java.net.*;
49 public class Client15 {
50 int i, flag, messagein;
51 static String iaddr;
52 static int port;
53 public Client15() {
54 try{
55
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
56
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
57
DataInputStream instream = new
DataInputStream(socket.getInputStream());
範例136:續5
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
58
59
60
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Input data on keyboard...");
61
62
63
64
65
66
while(true) {
i = br.read();
outstream.writeInt(i);
if (i == 64) {
flag = 1;
}
67
68
69
70
71
72
73
74
75
76
while (flag == 1) {
messagein = instream.readInt();
System.out.print((char)messagein);
if (messagein == 64) {
flag = 0;
System.out.println(" ");
}
}
}
}
範例136:續6
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
77 catch(IOException e){
78
System.out.println(e.getMessage());
79 }
80 }
81 public static void main(String args[]) {
82 if (args.length < 2){
83
System.out.println("USAGE: java Client15 [iaddr] [port]");
84
System.exit(1);
85 }
86 iaddr = args[0];
87 port = Integer.parseInt(args[1]);
88 Client15 ClientStart=new Client15();
89 }
90 }
第三篇
網路群播(Multi Broadcast)
第十六章
雜湊(Hashing)
•
•
•
•
•
•
•
16-1 簡介
16-2基礎概念(Basic Concepts)
16-3雜湊作為(Operation of Hashing)
16-4 Hashtable Class
16-5 Enumeration Interface
16-6 習題(Exercises)
16-1 簡介
•
• 雜湊(Hashing) 是一種快速搜尋之表格型態,將搜
尋鍵(Search Keys) 以雜湊函數(Hash Function) 處理
後,分置於各對應框籃(Buckets),可達到直接搜
尋之效率。
16-2基礎概念(Basic Concepts)
• 在搜尋概念中,雜湊(Hashing) 是最快速的一種搜
尋方式(Searching),可直逼直接搜尋(Directly
Searching),其搜尋複雜度(Complexity) 與資料多寡
無關,為O(1)。
範例137:設有一雜湊函數(Hash Function) HF = x
Mod 10,試以此HF設計雜湊表格索引(Hash Table
Index) 框籃(Bucket)。
範例138:參考範例137,設有資料搜尋鍵K = {3, 16,
21, 39},試以雜湊函數(Hash Function) HF = x Mod 10
建立雜湊表格索引(Hash Table Index) 框籃,並安排
資料雜湊鍵(Hash Key of Record)。
範例139:延續範例138,如果新增一個資料
搜尋鍵51,試請更新其雜湊結構(Hash
Structure)。
16-3雜湊作為(Operation of Hashing)
•
• 一旦雜湊函數(Hash Function) 設定雜湊表格索引
(Hash Table Index) 框籃(Bucket) 後,不再改變索引
框籃之結構,當有新增或刪除資料搜尋鍵時,僅
更新雜湊鏈之結構。
範例141:參考範例140,設有資料搜尋鍵K = {69, 74,
81, 91, 127, 136, 143, 151},雜湊函數(Hash Function)
HF為3位元(bits) 序列,試請建立雜湊表索引框籃,
並以各資料搜尋鍵Ki 之末端3位元對應雜湊表格索引
(Hash Table Index),安排資料雜湊鍵(Hash Key of
Record) 之位置。
範例142:延續範例141,將雜湊索引框
籃(Hash Index Bucket) 以最左端位元0與1
分段設置。
16-4 Hashtable Class
•
• java.util.Hashtable繼承(extends) 自
Dictionary→Object,此類別物件可儲存任何型態
、任何數量之資料、或物件,稱為元素(Elements)
,以一個搜尋鍵(key) 來識別或存取元素之內容。
範例143:試解釋以public Hashtable(int ca, float fac)
建立雜湊表格之結構,令其中參數ca = 16、fac = 0.5
。
範例144:設有檔案Ex16_4_1.java其功能為解釋雜湊實體方
法程序put(Object key, Object value) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex16_4_1 {
03 public static void main(String[] args) {
04 Hashtable ht = new Hashtable();
05 ht.put("Server", new String("163.15.40.242"));
06 ht.put("Client1", new String("163.15.40.243"));
07 ht.put("Client2", new String("163.15.40.244"));
08 System.out.println("ht.put() : " +
ht.put("Client1", new String("163.15.40.245")));
09 System.out.println("ht.put() : " +
ht.put("Client3", new String("163.15.40.245")));
10 }
11 }
範例145:設有檔案Ex16_4_2.java其功能為解釋一般雜湊實體方法
程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex16_4_2 {
03 public static void main(String[] args) {
04 Hashtable ht = new Hashtable();
05 ht.put("Server", new String("163.15.40.242"));
06 ht.put("Client1", new String("163.15.40.243"));
07 ht.put("Client2", new String("163.15.40.244"));
08 System.out.println("ht.isEmpty() : " + ht.isEmpty());
09 System.out.println("ht.size() : " + ht.size());
10 System.out.println("ht.contains() : " +
ht.contains(new String("163.15.40.242")));
11 System.out.println("ht.containsKey() : " + ht.containsKey("Server"));
12 System.out.println("ht.get() : " + ht.get("Server"));
13 }
14 }
16-5 Enumeration Interface
•
• java.util.Enumeration為介面,承作此介面之
物件可用於建立一些元素之串列,在網路
群播應用上,多用於配合雜湊表內元素串
列之獲得。
範例146:設有檔案Ex16_5.java其功能為解釋介面
Enumeration之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex16_5 {
03 public static void main(String[] args) {
04 Hashtable ht = new Hashtable();
05 ht.put("Server", new String("163.15.40.242"));
06 ht.put("Client1", new String("163.15.40.243"));
07 ht.put("Client2", new String("163.15.40.244"));
08 Enumeration enValue = ht.elements();
09 while(enValue.hasMoreElements()) {
10
String sValue = (String) enValue.nextElement();
11
System.out.println("enValue = " + sValue);
12 }
13 Enumeration enKey = ht.keys();
14 while(enKey.hasMoreElements()) {
15
String sKey = (String) enKey.nextElement();
16
System.out.println("enKey = " + sKey);
17 }
18 }
19 }
第十七章
執行緒同步並行(Threads Synchronized)
•
•
•
•
•
•
17-1 簡介
17-2 Runnable Interface
17-3 Thread Class
17-4 臨界區(Critical Section) 與synchronized
17-5 習題(Exercises)
17-1 簡介
• 在網路應用上,發生事件的區域範圍不僅廣大、
且數量也多不勝數,在程式設計上,我們必須考
量事件執行緒同步並行之安排,在CPU能力允許
下,各執行緒各自競爭進入CPU執行。
17-2 Runnable Interface
•
• java.lang.Runnable為介面,承作此介面之物件可定義執
行緒之行為,其與執行緒(Thread) 之關系與執行步驟如
下: (如範例147)
•
• (1) 設計一個承作Runnable之類別,其中有方法程序
run()。
• (2) 以該類別產生一個新物件。
• (3) 將該物件指定給予Thread建構子的一個參數,並產
生一個執行緒。
• (4) 當該執行緒開始執行時,也立即執行(1) 之run()。
範例147:設有檔案Ex17_2.java其功能為解釋介面Runnable
與Thread建構子之關係與運用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myRunnable implements Runnable {
02 public void run() {
03 System.out.println("Message by myRunnable");
04 }
05 }
06 public class Ex17_2 {
07 public Ex17_2() {
08 myRunnable testR = new myRunnable ();
09 Thread testTh = new Thread(testR);
10 testTh.start();
11 }
12 public static void main(String[] args) throws Exception {
13 Ex17_2 ServerStart=new Ex17_2();
14 }
15 }
17-3 Thread Class
•
• java.lang.Thread繼承(extends) 自Object、承
作(implements) 自Runnable,此類別物件可
產生獨立之執行緒,這些執行緒可與程式
的主執行緒同時並行運作。
範例148:設有檔案Ex17_3.java其功能為解釋Thread Class
之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Client1 implements Runnable {
02 public void run() {
03 System.out.println("Message by Client1");
04 }
05 }
06 class Client2 implements Runnable {
07 public void run() {
08 System.out.println("Message by Client2");
09 }
10 }
11 class Client3 implements Runnable {
12 public void run() {
13 System.out.println("Message by Client3");
14 }
15 }
範例148:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
16 public class Ex17_3 {
17 public Ex17_3() {
18 Client1 client1 = new Client1();
19 Thread thread1 = new Thread(client1);
20 thread1.start();
21
22
23
Client2 client2 = new Client2();
Thread thread2 = new Thread(client2);
thread2.start();
24
25
26
Client3 client3 = new Client3();
Thread thread3 = new Thread(client3);
thread3.start();
範例148:續2
•
•
•
•
•
•
•
•
•
•
•
•
27
28
29
Thread threadEx17_3 = new Thread();
int act = threadEx17_3.activeCount();
System.out.println("threadEx17_3.activeCount() = " + act);
30 Thread curr = threadEx17_3.currentThread();
31 System.out.println("threadEx17_3.currentThread() = " + curr.getName());
32 }
33 public static void main(String[] args) throws Exception {
34 Ex17_3 ServerStart=new Ex17_3();
35 }
36 }
17-4 臨界區(Critical Section) 與synchronized
•
• 每一執行緒(Thread) 之執行功能碼(Codes),均可
視為該執行緒之臨界區(CS Critical Section)。於臨
界區,執行緒可存取資源(Resource),如記憶體、
變數(Common Variables)、檔案(Files) 等。
第十八章
群播設計(Broadcast Programming)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
18-1 簡介
18-2 群播架構
18-3 伺服端(Server)
18-3-1網站平台(ServerSocket) / 連接平台(Socket)
18-3-2建立雜湊表(Hash Table)
18-3-3建立執行緒
18-4 發射端(Speaker)
18-4-1 連接平台(Socket)
18-4-2 緩衝器串流(InputStreamReader)
18-4-3網路輸出串流(DataOutputStream)
18-5 接收端(Receiver)
18-5-1 連接平台(Socket)
18-5-2 網路輸入串流(DataInputStream)
18-6 鍵盤輸入 / 群播印出
18-7 鍵盤輸入 / 群播檔案
18-8 習題(Exercises)
18-1 簡介
•
• 本章將以程式設計觀點,詳細介紹如何以
Java語言設計群播物件。前述之類別
Hashtable Class、介面Enumeration Interface
、介面Runnable Interface、類別Thread Class
、關鍵字synchronized等,均為設計程式之
基礎元件。
18-2 群播架構
•
• 如圖18-2,網路群播之流程為:(1) 由發射
端Speaker將資料Data發送至伺服端Server;
(2) 由伺服端Server將資料Data分送至各接收
端Receivers;(3) 各接收端Receivers接收資
料Data後依需要運用之。
18-3 伺服端(Server)
•
• 伺服器(Server) 是網路群播之轉接站,接收
來自發射端(Speaker) 傳來的資料,再轉發
給各接收端(Receivers)。伺服器也是群播架
構中最重要的節點,為了順利執行轉接資
料,需建立:(1) 網站平台(ServerSocket)/連
接平台(Socket)、(2) 輸入/輸出串流物件
(DataStream)、(3) 雜湊表(Hash Table)、(4)
並行執行緒(Synchronized Threads)。
範例149:設片斷程式如下,其功能為解釋如何設計群播執行緒。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class ServerRunnable implements Runnable {
02 … …
03 public void run() {
04 … …
05 synchronized(ht) {
06
Enumeration en = ht.elements();
07
while(en.hasMoreElements()) {
08
DataOutputStream outstream = (DataOutputStream)en.nextElement();
09
outstream.writeInt(message);
10
}
11 }
12 }
13 … …
14 }
15
16
17
18
19
… …
ServerRunnable sr = new ServerRunnable(socket, ht);
Thread thread = new Thread(sr);
thread.start();
… …
18-4 發射端(Speaker)
•
• 群播架構中,發射端(Speaker) 將鍵盤
(Keyboard) 輸入資料傳送至Server端,再轉
送至各接收端(Receivers)。為了順利執行需
建立:(1) 連接平台,連通伺服端;(2) 緩衝
器串流,讀取鍵盤輸入資料;(3) 網路輸出
串流,將資料由網路傳遞至伺服端。
18-5 接收端(Receiver)
•
• 接收端(Receiver) 接收從網路傳送來的資料
。需建立:(1) 連接平台,連通伺服端;(2)
網路輸入串流,接收從伺服端Server傳送來
的資料。
範例150:設有檔案Server18_6.java、Speaker18_6.java、Receiver18_6.java
其功能為解釋網路群播之應用(鍵盤輸入/群播印出)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server18_6.java:(建立:(1)網站平台(ServerSocket)/連接平台 (Socket)、
(2)輸入/輸出串流物件(DataStream)、(3)雜湊表(Hash Table)、(4) 並行執行緒
(Synchronized Threads)
001 import java.net.*;
002 import java.io.*;
003 import java.util.*;
004 public class Server18_6 {
005 private static ServerSocket SS;
006 private static int port;
007 private Hashtable ht = new Hashtable();
008 Socket socket;
009 public Server18_6() {
010 try {
011
SS = new ServerSocket(port);
012
System.out.println("Server is created and waiting Client to connect...");
範例150:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
013
014
015
016
017
018
019
020
021
022
023
024
025
while (true) {
socket = SS.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
ht.put(socket, outstream);
Thread thread = new Thread(new ServerRunnable(socket, ht));
thread.start();
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
範例150:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
026 public static void main(String[] args) {
027 if (args.length < 1) {
028 System.out.println("Usage: java Server18_6 [port]");
029 System.exit(1);
030 }
031 port=Integer.parseInt(args[0]) ;
032 Server18_6 ServerStart=new Server18_6();
033 }
034 }
035 class ServerRunnable implements Runnable {
036 private Socket socket;
037 private Hashtable ht;
範例150:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
038
039
040
041
public ServerRunnable(Socket socket, Hashtable ht) {
this.socket = socket;
this.ht = ht;
}
042 public void run() {
043 DataInputStream instream;
044 try {
045
instream = new DataInputStream(socket.getInputStream());
046
047
while (true) {
int message = instream.readInt();
範例150:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
048
049
050
051
052
053
054
055
056
057
058
059
060
061
}
062 }
synchronized(ht) {
Enumeration en = ht.elements();
while(en.hasMoreElements()) {
DataOutputStream outstream =
(DataOutputStream)en.nextElement();
try {
outstream.writeInt(message);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
範例150:續5
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
063 catch (IOException e) {
064
System.out.println(e.getMessage());
065 }
066 finally {
067
synchronized(ht) {
068
System.out.println("Remove connection: " + socket);
069
ht.remove(socket);
070
try {
071
socket.close();
072
}
073
catch (IOException e) {
074
}
075
}
076 }
078 }
079 }
範例150:續6
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Receiver18_6.java:(建立:(1)連接平台,連通伺服端;(2)網路輸入串流,接收從伺服端
Server傳送來的資料)
113 import java.io.*;
114 import java.net.*;
115 public class Receiver18_6 {
116 int messagein;
117 static String iaddr;
118 static int port;
119 public Receiver18_6() {
120 try{
121
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
122
DataInputStream instream = new
DataInputStream(socket.getInputStream());
123
while(true) {
124
messagein = instream.readInt();
125
System.out.print((char)messagein);
126
}
127 }
128
catch(IOException e){
範例150:續7
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
129
System.out.println(e.getMessage());
130 }
131 }
132 public static void main(String args[]) {
133 if (args.length < 2){
134
System.out.println("USAGE: java Receiver18_6 [iaddr] [port]");
135
System.exit(1);
136 }
137 iaddr = args[0];
138 port=Integer.parseInt(args[1]);
139 Receiver18_6 ReceiverStart=new Receiver18_6();
140 }
141 }
範例151:設計檔案Server18_7.java、Speaker18_7.java、Receiver18_7.java
其功能為解釋網路群播之應用(鍵盤輸入/群播檔案)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server18_7.java:內容與Server18_6.java相同,請參考範例150。
檔案Speaker18_7.java:內容與Speaker18_6.java相同,請參考範例150。
檔案Receiver18_7.java:(建立:(1)連接平台,連通伺服端;(2)網路輸入串流
,接收從伺服端Server傳送來的資料;(3)檔案輸出串流,將資料寫入指定之
檔案)
113 import java.net.*;
114 import java.io.*;
115 public class Receiver18_7 {
116 static String iaddr;
117 static int port;
118 static String outfilename;
119 int messagein;
120 public Receiver18_7() {
範例151:續1
• 121 try{
• 122
Socket socket=new Socket(InetAddress.getByName(iaddr),port);
• 123
DataInputStream instream = new
DataInputStream(socket.getInputStream());
• 124
FileWriter fw = new FileWriter(outfilename);
•
• 125
while(messagein != -1){
• 126
messagein = instream.readInt();
• 127
fw.write(messagein);
• 128
}
• 129
fw.flush();
• 130
System.out.println("Data written to File successfully!");
• 131 }
範例151:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
132 catch(IOException e){
133
System.out.println(e.getMessage());
134 }
135 }
136 public static void main(String args[]){
137 if(args.length < 3){
138
System.out.println("Usage: java Receiver18_7 [iaddr] [port]
[outfilename]");
139
System.exit(1);
140
}
141
iaddr = args[0];
142
port=Integer.parseInt(args[1]);
143
outfilename = args[2];
144
Receiver18_7 ReceiverStart=new Receiver18_7();
145 }
146 }
第十九章
視窗架構(Frame Structures)
•
•
•
•
•
•
19-1 簡介
19-2 Frame Class
19-3 TextField Class
19-4 BorderLayout Class
19-5 習題(Exercises)
19-1 簡介
• 圖型介面(Graphic User Interface、GUI) 是使用者與
系統執行功能之介面,使用者依照圖型介面視窗
的種類與位置、以滑鼠或鍵盤驅動系統功能之執
行。
19-2 Frame Class
•
• java.awt.Frame繼承(extends) 自
Window→Container→Component→Object,
此類別物件可建立一個視窗外框,配合網
路程式,美觀網路串流之應用。
範例152:設計檔案Ex19_2_1.java其功能為解釋視窗
框架與游標型態之建立。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_2_1 {
03 public Ex19_2_1() {
04
Frame frame = new Frame("myFrame");
05
frame.setCursor(Frame.HAND_CURSOR);
06
frame.setSize(300, 350);
07
frame.setVisible(true);
08 }
09 public static void main(String[] args) {
10
Ex19_2_1 teststart = new Ex19_2_1();
11 }
12 }
範例153:設計檔案Ex19_2_2.java其功能為解釋類別Frame
各方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_2_2 {
03 public Ex19_2_2() {
04 Frame frame = new Frame("myFrame");
05 frame.setCursor(Frame.HAND_CURSOR);
06 frame.setSize(300, 350);
07 frame.setVisible(true);
08
09
10
11
System.out.println("frame.getCursorType() : " + frame.getCursorType());
System.out.println("frame.getTitle() : " + frame.getTitle());
System.out.println("frame.isResizable() : " + frame.isResizable());
}
12 public static void main(String[] args) {
13 Ex19_2_2 teststart = new Ex19_2_2();
14 }
15 }
範例154:比較範例152,設計檔案Ex19_2_3.java其功能為
解釋繼承類別Frame之使用方法。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_2_3 extends Frame {
03 public Ex19_2_3() {
04
super("myFrame");
05
setCursor(Frame.HAND_CURSOR);
06
setSize(300, 350);
07
setVisible(true);
08 }
09 public static void main(String[] args) {
10
Ex19_2_3 teststart = new Ex19_2_3();
11 }
12 }
19-3 TextField Class
• java.awt.TextField繼承(extends) 自
TextComponent→Component→Object,此類
別物件可配合視窗框架允許產生一列文字
,包括初始字、新鍵入字、中文字。
範例155:設計檔案Ex19_3_1.java其功能為解釋視窗框架內之文字
應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_3_1 extends Frame {
03 public Ex19_3_1() {
04 super("myFrame");
05 setSize(300, 350);
06 setVisible(true);
07 TextField tf = new TextField("Initial word");
08 add(tf);
09 }
10 public static void main(String[] args) {
11
Ex19_3_1 teststart = new Ex19_3_1();
12 }
13 }
範例156:設計檔案Ex19_3_2.java其功能為解釋視窗框架文字之設定與讀取。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_3_2 extends Frame {
03 public Ex19_3_2() {
04 super("myFrame");
05 setSize(300, 350);
06 setVisible(true);
07
08
09
10
11 }
TextField tf = new TextField("Initial word");
add(tf);
tf.setText("The new setText");
System.out.println("tf.getText() = " + tf.getText());
12 public static void main(String[] args) {
13
Ex19_3_2 teststart = new Ex19_3_2();
14 }
15 }
19-4 BorderLayout Class
•
• java.awt.BorderLayout繼承自Object,此類別
可建立版面配置管理員之物件,搭配區域
常數EAST、WEST、NORTH、SOUTH與
CENTER,可將視窗框架內容劃分成5個版面
。(如範例157)
範例157:設計檔案Ex19_4.java其功能為解釋類別BorderLayout與區域常數EAST、
WEST、NORTH、SOUTH與CENTER,劃分視窗版面之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 class Ex19_4 extends Frame {
03 public Ex19_4() {
04 super("myFrame");
05
06
TextField tfE = new TextField("East Area");
add(tfE, BorderLayout.EAST);
07
08
TextField tfS = new TextField("South Area");
add(tfS, BorderLayout.SOUTH);
範例157:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
09
10
TextField tfW = new TextField("West Area");
add(tfW, BorderLayout.WEST);
11
12
TextField tfN = new TextField("North Area");
add(tfN, BorderLayout.NORTH);
13
14
TextField tfC = new TextField("Center Area");
add(tfC, BorderLayout.CENTER);
15 setSize(350, 300);
16 setVisible(true);
17 }
18 public static void main(String[] args) {
19 Ex19_4 teststart = new Ex19_4();
20 }
21 }
第二十章
圖型介面與網路對播(GUI and Intercross Transition)
•
•
•
•
•
•
•
•
•
20-1 簡介
20-2 ActionListener Interface
20-3 ActionEvent Class
20-4 Vector Class
20-5 圖型介面與視窗關閉
20-6 圖型介面與資料顯示
20-7 20-7 Server/Client對播程式設計
20-8 習題(Exercises)
20-1 簡介
•
• 本書已於第十五章探討網路對播之程式架構與設
計,於十九章探討視窗圖型界面,本章將綜合此
兩章之內容,設計一組網路對播之視窗圖型界面
,讓使用者輕鬆有效地操作網路對播。
20-2 ActionListener Interface
•
• java.awt.event.ActionListener為公用介面(Public
Interface),此介面用於回應Action動作,通常以方
法程序addActionListener(this) 將事件之傾聽功能加
入特定位置物件,再以方法程序actionPerformed()
配合發生在該位置物件之滑鼠或鍵盤事件,優先執
行之,即暫停執行其他執行緒(Threads) 或行程
(Processes)。(如範例158)
範例158:設計檔案Ex20_2.java其功能為解釋方法程序
addActionListener(this)、actionPerformed() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 import java.awt.event.*;
03 class Ex20_2 extends Frame implements ActionListener {
04 public Ex20_2() {
05 super("myFrame");
06
07
TextField tfS = new TextField("South Area");
add(tfS, BorderLayout.SOUTH);
08
09
TextField tfC = new TextField("Center Area");
add(tfC, BorderLayout.CENTER);
範例158:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
10
11
setSize(350, 300);
setVisible(true);
12 tfS.addActionListener(this);
13 }
14 public static void main(String[] args) {
15 Ex20_2 teststart = new Ex20_2();
16 }
17 public void actionPerformed(ActionEvent evt) {
18 System.out.println("An ActionEvent occurred on tfS");
19 }
20 }
20-3 ActionEvent Class
•
• java.awt.event.ActionEvent繼承(extends) 自
AWTEvent → EventObject → Object,此類別可
建立事件物件,通常都以前節之方法程序
actionPerformed(ActionEvent evt) 配合執行,當
系統有事件發生時,參數evt自動產生(如範例
158、159)。
範例159:設計檔案Ex20_3.java其功能為解釋事件物件與方法程序
getSource() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 import java.awt.event.*;
03 class Ex20_3 extends Frame implements ActionListener {
04 TextField input_Area = new TextField();
05 TextField record_Area = new TextField();
06 public Ex20_3() {
07 super("myFrame");
08
09
add(input_Area, BorderLayout.SOUTH);
add(record_Area, BorderLayout.CENTER);
範例159:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
10
11
setSize(350, 300);
setVisible(true);
12 input_Area.addActionListener(this);
13 }
14 public static void main(String[] args) {
15 Ex20_3 teststart = new Ex20_3();
16 }
17
18
19
20
21
22 }
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == input_Area) {
System.out.println("An ActionEvent occurred on input_Area");
}
}
20-4 Vector Class
•
• java.util.Vector繼承(extends) 自Object,此類
別可建立向量物件,類似陣列(Array),却較
陣列更具彈性:(1) 各元素可使用任意物件
,不像陣列、必須是相同的資料型態;(2)
可自動調整適當長度,不像陣列、必須是
設定長度(如範例160)。
範例160:設計檔案Ex20_4_1.java其功能為解釋系統可自動調整向
量物件成適當長度;使用者也可選擇性地設定其長度。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex20_4_1 {
03 public Ex20_4_1() {
04 Vector vec1 = new Vector(0);
05 System.out.println("vec1 Initial Capacity = " + vec1.capacity());
06
07
08
09
vec1.addElement("Here is No.0 Line");
vec1.addElement("Here is No.1 Line");
vec1.addElement("Here is No.2 Line");
System.out.println("vec1 Adjusted Capacity = " + vec1.capacity());
範例160:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
10
11
Vector vec2 = new Vector(0, 50);
System.out.println("vec2 Initial Capacity = " + vec2.capacity());
12
13
14
15
16 }
vec2.addElement("Here is No.0 Line");
vec2.addElement("Here is No.1 Line");
vec2.addElement("Here is No.2 Line");
System.out.println("vec2 Adjusted Capacity = " + vec2.capacity());
17 public static void main(String[] args) {
18 Ex20_4_1 teststart = new Ex20_4_1();
19 }
20 }
範例161:設計檔案Ex20_4_1.java其功能為解釋類別Vector
各實體方法程序之應用。
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex20_4_2 {
03 public Ex20_4_2() {
04 Vector vec = new Vector();
05
06
07
vec.addElement("Here is No.0 Line");
vec.addElement("Here is No.1 Line");
vec.addElement("Here is No.2 Line");
範例161:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
08
09
10
11
System.out.println("isEmpty() : " + vec.isEmpty());
System.out.println("elementAt(1) : " + vec.elementAt(1));
System.out.println("firstElement(0) : " + vec.firstElement());
System.out.println("lastElement(0) : " + vec.lastElement());
12 vec.insertElementAt("Here is the insert Object", 1);
13 System.out.println("elementAt(1) : " + vec.elementAt(1));
14 }
15 public static void main(String[] args) {
16 Ex20_4_2 teststart = new Ex20_4_2();
17 }
18 }
範例162:設計檔案Ex20_5.java其功能為解釋關閉視窗程式碼之設計。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 import java.awt.event.*;
03class Ex20_5 extends Frame {
04 public Ex20_5() {
05 super("myFrame");
06 setSize(300, 350);
07 setVisible(true);
08 addWindowListener(new WindowAdapter() {
09
public void windowClosing(WindowEvent evt) {
10
System.exit(0);
11
}
12 });
13 }
14 public static void main(String[] args) {
15
Ex20_5 teststart = new Ex20_5();
16 }
17 }
範例163:設計檔案Ex20_6.java其功能為解釋圖型介面各項功能之設計。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.awt.*;
02 import java.awt.event.*;
03 import java.util.*;
04 class Ex20_6 extends Frame implements ActionListener {
05 TalkRoom TalkRecord = new TalkRoom();
06 TextField TalkInput = new TextField();
07 public Ex20_6() {
08 super("myFrame");
09 try{
10
add(TalkRecord, BorderLayout.CENTER);
11
add(TalkInput, BorderLayout.SOUTH);
13
TalkInput.addActionListener(this);
範例163:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
15
setSize(500, 350);
setVisible(true);
16
17
18
19
20
21
22
23
24
25
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
範例163:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
26 public void actionPerformed(ActionEvent evt) {
27 if (evt.getSource() == TalkInput) {
28
try {
29
TalkRecord.PrintTalk(TalkInput.getText(), Color.red);
30
} catch (Exception e) {
31
System.out.println(e.getMessage());
32
}
33
TalkInput.setText(null);
34 }
35 }
36 public static void main(String args[]) {
37 Ex20_6 ServerStart=new Ex20_6();
38 }
39 }
範例163:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
40 class TalkRoom extends Component {
41 Vector PastLine = new Vector();
42 Vector NewLine = new Vector();
43 synchronized void PrintTalk(String s, Color c) {
44 NewLine.addElement(new SaveLine(s, c));
45 repaint();
46 }
47 public void paint(Graphics g) {
48 synchronized (this) {
49
while (NewLine.size() > 0) {
50
PastLine.addElement(NewLine.elementAt(0));
51
NewLine.removeElementAt(0);
52
}
53
while (PastLine.size() > 40) {
54
PastLine.removeElementAt(0);
55
}
56
}
57
FontMetrics fontM = g.getFontMetrics();
範例163:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
58
59
60
int margin = fontM.getHeight()/2;
int w = getSize().width;
int y = getSize().height-fontM.getHeight()-margin;
61
for (int i=PastLine.size()-1; i>=0; i--) {
62
SaveLine ShowLine = (SaveLine)PastLine.elementAt(i);
63
g.setColor(ShowLine.clr);
64
g.setFont(new Font(ShowLine.str,Font.BOLD,12));
65
g.drawString(ShowLine.str, margin, y+fontM.getAscent());
66
y -= fontM.getHeight();
67
}
68 }
69 }
70 class SaveLine {
71 String str;
72 Color clr;
73 SaveLine(String str, Color clr) {
74
this.str = str;
75
this.clr = clr;
76 }
77 }
範例164:設計檔案Server20_7.java、Client20_7.java其功能為解釋
圖型介面網路對播之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server20_7.java:
001 import java.awt.*;
002 import java.awt.event.*;
003 import java.io.*;
004 import java.net.*;
005 import java.util.*;
006 class Server20_7 extends Frame implements ActionListener, Runnable {
007 TalkRoom TalkRecord = new TalkRoom();
008 TextField TalkInput = new TextField();
009 ServerSocket SSocket;
010 Socket socket;
011 static int port;
012 DataOutputStream outstream;
013 DataInputStream instream;
範例164:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
014 public Server20_7() {
015 super("Server");
016 try{
017
SSocket = new ServerSocket(port);
018
System.out.println("Server is created and waiting Client to connect...");
019
020
socket = SSocket.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
021
022
outstream = new DataOutputStream(socket.getOutputStream());
instream = new DataInputStream(socket.getInputStream());
023
024
025
add(TalkRecord, BorderLayout.CENTER);
add(TalkInput, BorderLayout.SOUTH);
TalkInput.addActionListener(this);
026
addWindowListener(new WindowAdapter() {
範例164:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
027
028
029
030
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
031
032
033
034
035
036
037
038 }
setSize(500, 350);
setVisible(true);
new Thread(this).start();
}
catch (Exception e) {
e.printStackTrace();
}
039 public void actionPerformed(ActionEvent evt) {
040 if (evt.getSource() == TalkInput) {
041
try {
042
outstream.writeUTF("Server> "+TalkInput.getText());
043
TalkRecord.PrintTalk(TalkInput.getText(), Color.red);
044
} catch (Exception e) {
045
TalkRecord.PrintTalk("Connection is Interrupted", Color.green);
046
}
047
TalkInput.setText(null);
048 }
049 }
範例164:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
050 public void run() {
051 try {
052
while (true) {
053
String NetTransferLine = instream.readUTF();
054
TalkRecord.PrintTalk(NetTransferLine, Color.black);
055
}
056 }
057 catch (Exception e) {
058
TalkRecord.PrintTalk("Connection is Interrupted!", Color.green);
059 }
060 }
061 public static void main(String args[]) {
062 if (args.length < 1){
063
System.out.println("USAGE: java Server20_7 [port]");
064
System.exit(1);
065 }
066 port=Integer.parseInt(args[0]);
067 Server20_7 ServerStart=new Server20_7();
068 }
069 }
範例164:續4
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
070 class TalkRoom extends Component {
071 Vector PastLine = new Vector();
072 Vector NewLine = new Vector();
073 synchronized void PrintTalk(String s, Color c) {
074 NewLine.addElement(new SaveLine(s, c));
075 repaint();
076 }
077 public void paint(Graphics g) {
078 synchronized (this) {
079
while (NewLine.size() > 0) {
080
PastLine.addElement(NewLine.elementAt(0));
081
NewLine.removeElementAt(0);
082
}
083
while (PastLine.size() > 40) {
084
PastLine.removeElementAt(0);
085
}
086
}
範例164:續5
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
087
088
089
090
FontMetrics fontM = g.getFontMetrics();
int margin = fontM.getHeight()/2;
int w = getSize().width;
int y = getSize().height-fontM.getHeight()-margin;
091
for (int i=PastLine.size()-1; i>=0; i--) {
092
SaveLine ShowLine = (SaveLine)PastLine.elementAt(i);
093
g.setColor(ShowLine.clr);
094
g.setFont(new Font(ShowLine.str,Font.BOLD,12));
095
g.drawString(ShowLine.str, margin, y+fontM.getAscent());
096
y -= fontM.getHeight();
097
}
098 }
099 }
100 class SaveLine {
101 String str;
102 Color clr;
103 SaveLine(String str, Color clr) {
104
this.str = str;
105
this.clr = clr;
106 }
107 }
範例164:續6
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client20_7.java:
108 import java.awt.*;
109 import java.awt.event.*;
110 import java.io.*;
111 import java.net.*;
112 import java.util.*;
113 class Client20_7 extends Frame implements ActionListener, Runnable {
114 TalkRoom TalkRecord = new TalkRoom();
115 TextField TalkInput = new TextField();
116 Socket socket;
117 static String iaddr;
118 static int port;
119 DataOutputStream outstream;
120 DataInputStream instream;
範例164:續7
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
121 public Client20_7() {
122 super("Client");
123 try{
124
socket=new Socket(InetAddress.getByName(iaddr),port);
125
outstream = new DataOutputStream(socket.getOutputStream());
126
instream = new DataInputStream(socket.getInputStream());
127
128
129
add(TalkRecord, BorderLayout.CENTER);
add(TalkInput, BorderLayout.SOUTH);
TalkInput.addActionListener(this);
130
131
132
133
134
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
範例164:續8
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
135
136
137
138
139
140
141
142
setSize(500, 350);
setVisible(true);
new Thread(this).start();
}
catch (Exception e) {
e.printStackTrace();
}
}
143 public void actionPerformed(ActionEvent evt) {
144 if (evt.getSource() == TalkInput) {
145
try {
146
outstream.writeUTF("Client> "+TalkInput.getText());
147
TalkRecord.PrintTalk(TalkInput.getText(), Color.red);
148
} catch (Exception e) {
149
TalkRecord.PrintTalk("Connection is Interrupted", Color.green);
150
}
151
TalkInput.setText(null);
152 }
153 }
範例164:續9
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
154 public void run() {
155 try {
156
while (true) {
157
String NetTransferLine = instream.readUTF();
158
TalkRecord.PrintTalk(NetTransferLine, Color.black);
159
}
160 }
161 catch (Exception e) {
162
TalkRecord.PrintTalk("Connection is Interrupted!", Color.green);
163 }
164 }
165 public static void main(String args[]) {
166 if (args.length < 2){
167
System.out.println("USAGE: java Client20_7 [iaddr] [port]");
168
System.exit(1);
169 }
170 iaddr = args[0];
171 port=Integer.parseInt(args[1]);
172 Client20_7 ClientStart=new Client20_7();
173 }
174 }
175 class TalkRoom extends Component {
範例164:續10
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
176 Vector PastLine = new Vector();
177 Vector NewLine = new Vector();
178 synchronized void PrintTalk(String s, Color c) {
179 NewLine.addElement(new SaveLine(s, c));
180 repaint();
181 }
182 public void paint(Graphics g) {
183 synchronized (this) {
184
while (NewLine.size() > 0) {
185
PastLine.addElement(NewLine.elementAt(0));
186
NewLine.removeElementAt(0);
187
}
188
while (PastLine.size() > 40) {
189
PastLine.removeElementAt(0);
190
}
191 }
範例164:續11
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
192
193
194
195
FontMetrics fontM = g.getFontMetrics();
int margin = fontM.getHeight()/2;
int w = getSize().width;
int y = getSize().height-fontM.getHeight()-margin;
196 for (int i=PastLine.size()-1; i>=0; i--) {
197
SaveLine ShowLine = (SaveLine)PastLine.elementAt(i);
198
g.setColor(ShowLine.clr);
199
g.setFont(new Font(ShowLine.str,Font.BOLD,12));
200
g.drawString(ShowLine.str, margin, y+fontM.getAscent());
201
y -= fontM.getHeight();
202 }
203 }
204 }
範例164:續12
•
•
•
•
•
•
•
•
205 class SaveLine {
206 String str;
207 Color clr;
208 SaveLine(String str, Color clr) {
209
this.str = str;
210
this.clr = clr;
211 }
212 }
第二十一章
圖型介面與網路群播(GUI and Multi Broadcast)
•
• 21-1 簡介
• 21-2 Server/Client群播程式設計
• 21-3 習題(Exercises)
21-1 簡介
•
• 一個Server端伺服器,多個Client端電腦,當各Client
端向Server端伺服器網站註冊報到後,彼此即可相
互群播傳遞資料,如是執行情形我們已於十八章曾
作基礎架構之討論。本章再依前述各章節之經驗,
將群播原理執行於圖形框架視窗顯示上。於Server
端建立一Hash Table管理各Client端網路送來的資料
,再將資料網路分流送給各Client端,猶如一個網路
會議室。
範例164:設計檔案Server21.java、Client21.java其功能為解釋圖型
介面網路群播之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Server21.java:
001 import java.net.*;
002 import java.io.*;
003 import java.util.*;
004 public class Server21 {
005 private static ServerSocket SSocket;
006 private static int port;
007 private Hashtable ht = new Hashtable();
008 Socket socket;
009 public Server21() throws IOException {
010 try {
011
SSocket = new ServerSocket(port);
012
System.out.println("Server is created and waiting Client to connect...");
範例164:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
013
014
015
while (true) {
socket = SSocket.accept();
System.out.println("Client IP = " +
socket.getInetAddress().getHostAddress());
016
DataOutputStream outstream = new
DataOutputStream(socket.getOutputStream());
017
ht.put(socket, outstream);
018
Thread thread = new Thread(new ServerThread(socket, ht));
019
thread.start();
020
}
021 }
022 catch (IOException ex) {
023
ex.printStackTrace();
024 }
025 }
範例164:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
026 public static void main(String[] args) throws Exception {
027 if (args.length < 1) {
028
System.out.println("Usage: java Server21 [port]");
029
System.exit(1);
030 }
031 port=Integer.parseInt(args[0]) ;
032 Server21 ServerStart=new Server21();
033 }
034 }
035 class ServerThread extends Thread implements Runnable {
036 private Socket socket;
037 private Hashtable ht;
範例164:續3
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
038
039
040
041
public ServerThread(Socket socket, Hashtable ht) {
this.socket = socket;
this.ht = ht;
}
042 public void run() {
043 DataInputStream instream;
044 try {
045
instream = new DataInputStream(socket.getInputStream());
046
047
048
049
050
051
052
053
054
while (true) {
String message = instream.readUTF();
System.out.println("Message: " + message);
synchronized(ht) {
for (Enumeration e = ht.elements(); e.hasMoreElements(); ) {
DataOutputStream outstream = (DataOutputStream)e.nextElement();
try {
outstream.writeUTF(message);
}
範例164:續5
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
055
catch (IOException ex) {
056
ex.printStackTrace();
057
}
058
}
059
}
060
}
061 }
062 catch (IOException ex) {
063 }
064 finally {
065
synchronized(ht) {
066
System.out.println("Remove connection: " + socket);
067
ht.remove(socket);
068
try {
069
socket.close();
070
}
071
catch (IOException ex) {
072
}
073
}
074 }
075 }
076 }
範例164:續6
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
檔案Client21.java:
077 import java.awt.*;
078 import java.awt.event.*;
079 import java.io.*;
080 import java.net.*;
081 import java.util.*;
082 class Client21 extends Frame implements ActionListener, Runnable {
083 TalkRoom TalkWork = new TalkRoom();
084 TextField TalkInput = new TextField();
085 Socket socket;
086 static String iaddr;
087 static int port;
088 static String user;
089 DataOutputStream outstream;
090 DataInputStream instream;
範例164:續7
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
091 public Client21() {
092 super("Client");
093 try{
094
socket=new Socket(InetAddress.getByName(iaddr),port);
095
outstream = new DataOutputStream(socket.getOutputStream());
096
instream = new DataInputStream(socket.getInputStream());
097
098
099
add(TalkWork, BorderLayout.CENTER);
add(TalkInput, BorderLayout.SOUTH);
TalkInput.addActionListener(this);
100
101
102
103
104
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
範例164:續8
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
105
106
107
108
109
110
111
112
setSize(500, 350);
setVisible(true);
new Thread(this).start();
}
catch (Exception e) {
e.printStackTrace();
}
}
113 public void actionPerformed(ActionEvent evt) {
114 if (evt.getSource() == TalkInput) {
115
try {
116
outstream.writeUTF(user+"> "+TalkInput.getText());
117
TalkWork.PrintTalk(TalkInput.getText(), Color.red);
118
} catch (Exception e) {
119
System.out.println(e.getMessage());
120
}
121
TalkInput.setText(null);
122
}
123 }
124 public void run() {
範例164:續9
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
125
126
127
128
129
130
131
132
133
134 }
try {
while (true) {
String NetTransferLine = instream.readUTF();
TalkWork.PrintTalk(NetTransferLine, Color.black);
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
135 public static void main(String args[]) {
136 if (args.length < 3){
137
System.out.println("USAGE: java Client21 [iaddr] [port] [user]");
138
System.exit(1);
139 }
140 iaddr= args[0];
141 port=Integer.parseInt(args[1]);
142 user=args[2];
143 Client21 ClientStart=new Client21();
144 }
145 }
範例164:續10
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
146 class TalkRoom extends Component {
147 Vector PastLine = new Vector();
148 Vector NewLine = new Vector();
149 synchronized void PrintTalk(String s, Color c) {
150 NewLine.addElement(new SaveLine(s, c));
151 repaint();
152 }
153 public void paint(Graphics g) {
154 synchronized (this) {
155
while (NewLine.size() > 0) {
156
PastLine.addElement(NewLine.elementAt(0));
157
NewLine.removeElementAt(0);
158
}
159
while (PastLine.size() > 40) {
160
PastLine.removeElementAt(0);
161
}
162
}
範例164:續11
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
163
164
165
166
FontMetrics fontM = g.getFontMetrics();
int margin = fontM.getHeight()/2;
int w = getSize().width;
int y = getSize().height-fontM.getHeight()-margin;
167
for (int i=PastLine.size()-1; i>=0; i--) {
168
SaveLine ShowLine = (SaveLine)PastLine.elementAt(i);
169
g.setColor(ShowLine.clr);
170
g.setFont(new Font(ShowLine.str,Font.BOLD,12));
171
g.drawString(ShowLine.str, margin, y+fontM.getAscent());
172
y -= fontM.getHeight();
173
}
174 }
175 }
範例164:續12
•
•
•
•
•
•
•
•
176 class SaveLine {
177 String str;
178 Color clr;
179 SaveLine(String str, Color clr) {
180 this.str = str;
181 this.clr = clr;
182 }
183 }