bài giảng lập trình mạng
TRANSCRIPT
![Page 1: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/1.jpg)
HỌC PHẦN
LẬP TRÌNH MẠNG
CHƯƠNG 1: TỔNG QUAN MẠNG MÁY TÍNH & LẬP TRÌNH MẠNG
1
![Page 2: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/2.jpg)
Giới thiệu môn học
• Mục tiêu
• Tài liệu tham khảo:
1.Jan Graba, An Introduction to Network Programming with Java, Springer, 2007
2. Elliotte Rusty Harold, java network programming, 3rd
Edition, O'Reilly, 2004
2
![Page 3: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/3.jpg)
Trao đổi thông tin trên thực tế
3
![Page 4: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/4.jpg)
Các lớp giao thức Internet
4
![Page 5: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/5.jpg)
Giao tiếp trên hệ thống truyền thông
5
![Page 6: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/6.jpg)
Trao đổi thông tin theo mô hình
6
![Page 7: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/7.jpg)
Lớp vật lý
7
![Page 8: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/8.jpg)
Lớp Data Link
8
![Page 9: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/9.jpg)
Kết nối qua từng chặng
9
![Page 10: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/10.jpg)
Giao tiếp trên mỗi chặng
10
![Page 11: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/11.jpg)
Lớp mạng
11
![Page 12: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/12.jpg)
Kết nối từ nguồn đến đích
12
![Page 13: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/13.jpg)
Ví dụ
13
![Page 14: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/14.jpg)
Lớp truyền tải
14
![Page 15: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/15.jpg)
Chuyển phát tin cậy một thông điệp
15
![Page 16: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/16.jpg)
Ví dụ
16
![Page 17: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/17.jpg)
Lớp ứng dụng
17
![Page 18: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/18.jpg)
Tóm tắt nhiệm vụ của từng lớp giao thức
18
![Page 19: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/19.jpg)
Mô hình OSI
19
![Page 20: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/20.jpg)
Hai giao tiếp chính của một phần mềm giao thức
Giao thức lớp N+1 Giao thức lớp N+ 1
Giao thức NGiao thức N
Giao tiếp ngang hàng
Máy A Máy B
20
![Page 21: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/21.jpg)
Hai chế độ hoạt động của giao thức
• Connection-oriented• Giao tiếp ngang hàng có duy trì một đường đi cố định
• Datagram (connectionless)• Giao tiếp ngang hàng không có đường nối cố định
• Mỗi gói tin có thể đi trên các con đường khác nhau đến đích
21
![Page 22: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/22.jpg)
Tổng quan lập trình mạng (1/2)
• Mạng máy tính có hai phần
• Vật lý (phần cứng)
• Luận lý (phần mềm)
• Giao tiếp vật lý
• Chuẩn giao tiếp vật lý
• Chip logic có thể lập trình
• Chương trình điều khiển (driver hay có sẵn trong BIOS, trong hệ
điều hành)
• Lập trình: các driver, các API
22
![Page 23: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/23.jpg)
Tổng quan lập trình mạng (2/2)
• Giao tiếp luận lý
• Giao thức mức thấp: Đặc tả giao thức trong các RFC, lập trình giao
thức
• Giao thức mức cao: Đặc tả giao thức trong các RFC, lập trình giao
thức.
• Ứng dụng mạng: Các chương trình tiện ích của người dùng trao
đổi thông tin hay sử dụng dịch vụ qua mạng, lập trình dựa vào API
23
![Page 24: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/24.jpg)
Giao tiếp liên tiến trình
• Process
• Hệ thống đa nhiệm
• Cơ chế cho phép giao tiếp giữa các process trong hệ thống đa nhiệm: IPC (Inter-Process Communication)
24
![Page 25: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/25.jpg)
Hai loại giao tiếp IPC
• Các process trên cùng một máy
kernel
Process 1 Process 2
25
![Page 26: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/26.jpg)
Hai loại giao tiếp IPC
• Hai tiến trình trên hai máy khác nhau
kernel
Process 1
kernel
Process 2
Các kernel thỏa thuận với nhau các qui tắc trao đổi thông tinCác qui tắc là một phần của giao thức
26
![Page 27: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/27.jpg)
Ứng dụng mạng
• Chương trình tạo ra các tiện ích (dịch vụ) phục vụ người dùng• Tiện ích về lưu trữ và truy xuất tập tin (ftp)
• Tiện ích đầu cuối từ xa (telnet)
• Tiện ích in ấn
• Tiện ích duyệt web
• Ứng dụng mạng được xây dựng dựa vào mô hình ứng dụng : peer-to-peer, client-server, lai ghép.
27
![Page 28: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/28.jpg)
Mô hình client-server
• Ứng dụng cấu thành từ hai phần:• Quá trình chuyên cung ứng sự phục vụ là server
• Quá trình chuyên yêu cầu phục vụ từ server gọi là client
28
![Page 29: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/29.jpg)
Hai chế độ giao tiếp
• Chế độ blocking (nghẽn): khi client hay server phát ralệnh send gửi thông điệp, quá trình client hay servertương ứng sẽ bị treo cho đến khi phía nhận phát lệnhreceive tiếp nhận thông điệp. Tương tự khi gọi lệnhreceive mà chưa có send cũng sẽ vào trạng thái treo chođến khi có lệnh send từ xa gửi thông điệp đến.
29
![Page 30: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/30.jpg)
Hai chế độ giao tiếp (tt)
• Chế độ nonblocking: khi phát ra lệnh truyền thông, quátrình client hay server vẫn tiếp tục được thực thi màkhông bị treo
30
![Page 31: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/31.jpg)
• Các chức năng trong một chương trình ứng dụng gồm :
• Giao diện nhập liệu (user interface service)
• Tính toán, xử lý thông tin theo qui định (business rule service)
• Truy vấn và lưu trữ thông tin (data storage service)
• Ở mức vật lý các chức năng này được lập trình trong một
hay nhiều tập tin tùy theo kiểu kiến trúc :
• Kiến trúc một tầng
• Kiến trúc hai tầng
• Kiến trúc ba tầng
Kiến trúc chương trình
31
![Page 32: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/32.jpg)
Kiến trúc một tầng (single-tier architecture)
• Cả ba chức năng của phần mềm ứng dụng đều được lập
trình trong cùng một tập tin
32
![Page 33: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/33.jpg)
Kiến trúc hai tầng (two-tier architecture)
• Được gọi là kiến trúc client server
• Gồm 2 chương trình thực thi
• Trên hai máy tính khác nhau hay trên cùng một máy tính
• Mỗi ứng dụng phải có giao thức (protocol) được định nghĩa để giaotiếp trao đổi thông tin
• Thông thường client đảm nhận user interface
• Server đảm nhận data storage
• Chức năng business rule có thể• Lập trình tạo ra trên client � Fat client
• Lập trình tạo ra trên server � Fat server
33
![Page 34: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/34.jpg)
34
Fat Client
Fat Server
![Page 35: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/35.jpg)
Kiến trúc 3 tầng
35
![Page 36: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/36.jpg)
NHẮC LẠI NGÔN NGỮ JAVA
36
![Page 37: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/37.jpg)
Đặc điểm
• Ngôn ngữ cấp cao
• Thuần hướng đối tượng
• Có thể thực thi trên các hệ điều hành khác nhau
• Đa luồng
• Phân tán
• Ngôn ngữ động
• Đơn giản, dễ học, kiến trúc chương trình dễ hiểu
37
![Page 38: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/38.jpg)
Máy ảo java (JMV)
• Đảm bảo cho chương trình chạy trên nhiều nền tảng khác nhau.
• ByteCode là ngôn ngữ máy của máy ảo giống các mã lệnh nhị phân
của máy thật.
• Một chương trình được viết được lưu thành tập tin có phần mở rộng
là .java, phải được biên dịch thành tập tin thực thi trên máy ảo java có
phần mở rộng là .class.
• Tập tin thực thi chứa các chỉ thị ở dạng ByteCode mà máy ảo java
hiểu được.
• Khi thực thi chương trình, máy ảo dịch các ByteCode thành mã nhị
phân của máy tính thật
• => máy ảo là trình biên dịch
38
![Page 39: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/39.jpg)
Hai kiểu ứng dụng
• Applet• Chương trình nhúng vào trang web, được tải từ webserver về máy
client
• Application
• Chương trình thực thi trực tiếp trên máy ảo java
39
![Page 40: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/40.jpg)
Bộ công cụ phát triển ứng dụng JDK
• Được cung cấp miễn phí bởi JavaSoft (Sun), javasoft.com
• Mỗi loại hệ điều hành sẽ có bộ JDK tương ứng
• Các chương trình thực thi quan trọng của JDK
• javac: biên dịch chương trình nguồn thành tập tin thực thi trên máy ảo
• java: làm cho máy ảo biên dịch mã ByteCode thành mã thực thi trên máy thật
• appletviewer: thông dịch, thực thi các chương trình applet
• jdb: trình gở rối
• javadoc: tự động tạo tài liệu chú thích chương trình nguồn
• rmic: tạo Stub cho ứng dụng kiểu RMI
• rmiregistry: thực hiện danh bạ trong RMI
40
![Page 41: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/41.jpg)
Kiểu dữ liệu• Số:
• Ký tự char• 2byte
• Kiểu chuỗi String• Là lớp thuộc thư viện chuẩn của java, java.lang.String
• Kiểu logic boolean: 2 giá trị true và false• Kiểu mảng
• khai báo int[] a; hay int a[]; int maTran[][]• Khởi tạo biến a= new int[10]; maTran=int[9][9]• Sử dụng mảng int i=a[10]; int x=maTran[2][5]
41
![Page 42: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/42.jpg)
Các phép toán cơ bản
Tương tự như C++
-Toán số học: +,-,*,/,%,=,++,--,+=,-=,/=,%=
-Toán logic: ==,!=,&&,||,!,>,<,>=,<=
-Toán trên bit: &,|,^,<<,>>,~
-Điều kiện: ?:
-Chuyển đổi kiểu (ép kiểu): (kiểu mới)
42
![Page 43: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/43.jpg)
Nguyên tắc đặt tên
• Tên phân biệt chữ hoa và chữ thường
• Dùng chữ cái, chữ số, ký tự _ và dấu $
• Không bắt đầu bằng chữ số
Tên lớp: Viết hoa các ký tự đầu của từ
Ví dụ: InputStream, WhileDemo
Tên biến, tên hằng hay tên phương thức: từ đầu tiên viết
thường, các từ tiếp theo viết hoa ký tự đầu
Ví dụ maLop, giaTriDau, getInputStream(), maLop,
43
![Page 44: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/44.jpg)
Chương trình ứng dụng kiểu Application
• Ngôn ngữ thuần đối tượng
• Một chương trình ứng dụng chỉ có một lớp thực thi
• Lớp thực thi phải có tên trùng với tập tin chứa nó, phải
khai báo public và chứa phương thức:
public static void main (String[] args) {
……
}
Là phương thức được thực thi đầu tiên
44
![Page 45: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/45.jpg)
Cài đặt hệ thống
• Download JRE và JDK từ javasoft.com phù hợp với hệ
điều hành
• Cài đặt, chọn nơi cài đặt ví dụ C:\jdk1.6.0_33
• Thiết lập biến môi trường
• PATH = C:\jdk1.6.0_33\bin;
• CLASSPATH = C:\jdk1.4\lib;.;
45
![Page 46: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/46.jpg)
Lập trình
• HelloWorld
• Dùng JDK để biên dịch và thực thi
public class HelloWorld {
public static void
main(String args[]) {
System.out.print("Hello World!\n");
}
}
46
![Page 47: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/47.jpg)
Ví dụ in ra màn hình
Dùng
System.out.print (tham số 1+ tham số 2 + tham số 3 + …)
public class InManHinh {
public static void main(String args[]) {
int i = 1234;
String str = " la Lap trinh mang";
char ch = ‘A';
System.out.print('\n'+ “Ma mon hoc:"
+ch+ i + str);
}
}
47
![Page 48: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/48.jpg)
Ví dụ nhập ký tự từ bàn phím
Dùng System.in.read();
import java.io.*;
public class KeyRead {
public static void main(String args[]) {
try {
int ch = System.in.read();
System.out.print("Ky tu " + (char)ch + "
co ma ascii = "+ch);
} catch(IOException ie) {
System.out.print("Error " + ie) ;
}
}
}
48
![Page 49: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/49.jpg)
Cấu trúc if
Cú pháp:
if (Condition) {
// Các lệnh sẽ được thực hiện nếu giá trị của Condition là true
}
if (Condition) {
// Các lệnh sẽ được thực hiện nếu giá trị của Condition là true
} else {
// Các lệnh sẽ được thực hiện nếu giá trị của Condition là false
}
49
![Page 50: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/50.jpg)
Ví dụ lệnh ifimport java.io.*; public class IfDemo {
public static void main(String args[]) { System.out.print("Vui long nhap mot ky tu:"); try {
int ch = System.in.read(); if (ch == 'A') {
System.out.print("Ban rat may man !"); } else {
System.out.print("Ban khong gap may !"); }
} catch(IOException ie) { System.out.print("Error:"+ie);
} }
}
50
![Page 51: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/51.jpg)
Lệnh whileCú pháp while (condition) {
// nếu condition có giá trị là true, thì các tác vụ ở đây sẽ được lặp lại }
Ví dụ
import java.io.*; public class WhileDemo {
public static void main(String args[]) { int num = '9'; while (num > '0') {
System.out.print((char)num +" "); num--;
} }
}
51
![Page 52: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/52.jpg)
Lệnh do-whlieCú pháp
do { // Lặp lại các tác vụ ở đây cho đến khi điều kiện condition có giá trị là false
} while (condition)
Ví dụimport java.io.*; public class DoWhileDemo {
public static void main(String args[]) { int num = '9'; do {
System.out.print((char)num +" "); num--;
} while (num > '0'); }
}
52
![Page 53: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/53.jpg)
Lệnh for
Cú pháp
for (operation1; condition; operation2){
// Các tác vụ được lặp lại
}
Tương đương như cấu trúc sau:
operation1;
while (condition) {
// Các tác vụ được lặp lại
operation2;
}
53
![Page 54: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/54.jpg)
Ví dụ lệnh for
import java.io.*;
public class ForDemo {
public static void main(String args[]) {
for(int num = '9'; num>'0'; num --)
{
System.out.print((char)num +"
");
}
}
}
54
![Page 55: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/55.jpg)
Bài tập
• Tìm một ứng dụng mạng bất kỳ và mô tả :
• Các chức năng hỗ trợ của ứng dụng
• Kiến trúc của ứng dụng
• Giao thức hỗ trợ ứng dụng
• Xác định các trạng thái của các máy và sơ đồ hoạt động chuyển
đổi giữa các trạng thái (Chu trình hoạt động của mỗi máy liên quan
trong ứng dụng mà qua đó xác định giải thuật của chương trình)
55
![Page 56: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/56.jpg)
MỘT SỐ KỸ THUẬT THÔNG DỤNG
1
![Page 57: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/57.jpg)
Nội dung
• STREAM
• THREAD VÀ MULTITHREAD
• PIPE
2
![Page 58: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/58.jpg)
Kỹ thuật giao tiếp dùng Stream
• Khái niệm stream
• Input Stream và Output Stream
• Stream trong java
3
![Page 59: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/59.jpg)
Khái niệm Stream
• Stream là dòng liên tục, có thứ tự của các bytes dữ
liệu chảy giữa chương trình và các thiết bị ngoại vi
• Dùng stream có thể kết nối nhiều thiết bị ngoại vi với
chương trình
4
![Page 60: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/60.jpg)
Input Stream và Output Stream
• Nếu dòng dữ liệu trong Stream có hướng chảy từ thiết bị
ngoại vi vào chương trình thì ta nói đây là Stream nhập
(Input Stream)
• Chảy theo chiều ngược lại là Stream xuất (Output
Stream)
5
![Page 61: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/61.jpg)
outT
oSer
ver
to network from network
inF
rom
Ser
ver
inF
rom
Use
r
keyboard monitor
Process
clientSocket
inputstream
inputstream
outputstream
TCPsocket
6
![Page 62: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/62.jpg)
Cách giao tiếp dùng stream
• Để giao tiếp, trước tiên chương trình phải lấy được các
stream nhập / xuất gắn với thiết bị.
• Sau đó,
• chương trình có thể gởi dữ liệu ra ngoại vi bằng thao tác ghi vào
Stream xuất của thiết bị.
• có thể nhận dữ liệu từ ngoại vi bằng thao tác đọc Stream nhập của
thiết bị .
7
![Page 63: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/63.jpg)
Stream trong java
• Đối với Java, các thiết bị đều có Stream nhập/Stream xuất nối
với nó.
• Java hỗ trợ hai các lớp stream cơ bản trong gói java.io là:
• java.io.InputStream: Stream nhập
• java.io.OutputStream: Stream xuất
8
![Page 64: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/64.jpg)
Lớp java.io.InputStream
• Là loại nhận dữ liệu từ bên ngoài
• Có phương thức:
int read() throws IOException
Đọc 1 byte từ Stream
Return 0-255 : Mã ASCII của byte nhận được từ ngoại vi
-1 : Stream đã kết thúc, không còn dữ liệu.
• Đối với java System.in là một InputStream nối với bàn phím
9
![Page 65: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/65.jpg)
Ví dụ 1import java.io.*; public class InStream1 {
public static void main(String args[]) { InputStream is = System.in; // KeyBoard = System.in while (true) {
try { int ch = is.read(); if (ch ==-1 || ch =='q') break; System.out.print((char)ch);
} catch (IOException ie) { System.out.print("Error: "+ie);
} }
} }
10
![Page 66: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/66.jpg)
Lớp java.io.InputStream (tt)int read(byte b[]) throws IOException
Đọc tất cả các byte hiện có trong Stream vào mảng b.
Return 0-255: Số lượng byte đọc được.
-1 : Stream đã kết thúc, không còn dữ liệu.
int read(byte b[], int offset, int len)
Đọc len byte từ Stream hiện tại, lưu vào trong mảng b bắt đầu từ vị trí offset
Return: số lượng byte đọc được.
-1 : Stream đã kết thúc.
int available()
Trả về số lượng byte hiện có trong Stream mà không làm nghẽn chương trình
11
![Page 67: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/67.jpg)
Ví dụ 2import java.io.*; public class InStream2 {
public static void main(String args[]) { InputStream is = System.in; //KeyBoard = System.in while (true) {
try { int num = is.available(); if (num > 0){
byte[] b = new byte[num]; int result = is.read(b); if (result == -1) break; String s = new String(b); System.out.print(s);
} else { System.out.print('.'); }
} catch (IOException ie) { System.out.print("Error: "+ie);
} }
} }
12
![Page 68: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/68.jpg)
Lớp java.io.OutputStream • Cho phép chương trình xuất dữ liệu ra thiết bị ngoài có các phương thức:
void write(int b) throws IOException
• Viết byte b vào Stream hiện tại,
• Return : void
void write (byte[] b) throws IOException
• Viết tất cả các phần tử của mảng b vào Stream hiện tại
• Return : void
void write (byte[] b, int offset, int len) throws IOException:
•Viết len phần tử trong mảng b vào Stream hiện tại, bắt đầu từ
phần tử có chỉ số là offset của mảng.
•Return : void
System.out là một OutputStream nối với màn hình
13
![Page 69: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/69.jpg)
Nhập chuỗi từ một InputStream• Vấn đề: chỉ cung cấp phương thức đọc byte và mảng
byte• Lớp java.io.InputStreamReader: Là cầu nối để chuyển
InputStream dạng byte sang InputStream dạng các ký tự
• Lớp java.io.BufferedReader: Hỗ trợ việc đọc văn bản từmột InputStream dạng ký tự
• Phương thức String readLine() throws IOException củaBufferedReader cho phép đọc dòng văn bản kế tiếp trongInputStream
14
![Page 70: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/70.jpg)
Ví dụ 3import java.io.*; public class ReadLine{
public static void main(String args[]) { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while (true) {
try { String line = br.readLine(); if (line == null ) break; System.out.print(line);
} catch (IOException ie) { System.out.print("Error: "+ie);
} }
} }
15
![Page 71: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/71.jpg)
Xuất chuỗi ra một OutputStream
• Vấn đề: tương tự InputStream
• Để có thể gởi được chuỗi ra một OutputStream ta phải sử dụng
lớp java.io.PrintWriter
• Phải đổi OutputStream dạng byte sang dạng ký tự, và viết chuỗi
vào Output Stream dang ký tự
• Ví dụ in chuỗi ra màn hình
16
![Page 72: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/72.jpg)
Ví dụ 4: in chuỗi ra màn hìnhimport java.io.*;
public class PrintString {
public static void main(String args[]) {
OutputStream os = System.out;
PrintWriter pw = new PrintWriter(os);
pw.write("This is a string \r\n");
pw.println("This is a line");
pw.write("Bye! Bye!");
pw.flush();
}
}
17
![Page 73: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/73.jpg)
Thread
• Khái niệm
• Multithread
• Thread trong java
18
![Page 74: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/74.jpg)
Khái niệm
• Thread là đơn vị chương trình được dùng trong cơ chế
xử lý song song nhằm cải thiện hiệu năng của hệ thống
máy tính
• Là đơn vị cơ bản sử dụng CPU
• Các Process được chia thành các thread, có bộ đếm
chương trình, các thanh ghi trạng thái và stack riêng
• Các thread của một process có chung không gian địa chỉ.
19
![Page 75: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/75.jpg)
Multithread
• Một chương trình có thể mở nhiều threat đồng thời• Server sử dụng multithread để phục vụ đồng thời nhiều yêu cầu từ server.
Dispatcher thread
Worker thread
Worker thread
Worker thread
port
client
client
client
request
20
![Page 76: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/76.jpg)
Thread trong java
• Thread trong java là đối tượng thuộc lớp java.lang.Thread
• Cài đặt thread trong chương trình= tạo lớp con của lớp
java.lang.Thread
• Ba phương thức cơ bản điều khiển thread
• public native synchronized void start()
• Chuẩn bị mọi thứ để thực hiện
• public void run()
• Thực hiện công việc cụ thể của thread, được kích hoạt một cách tự động bởi phương
thức start()
• public final void stop()
• Kết thúc luồng
21
![Page 77: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/77.jpg)
public class MyThread extends Thread{ String name; int n;
MyThread(String name, int n) { this.name = name; this.n = n; System.out.println("Thread "+name+" has been created ....!"); start();
} public void run(){
for(int i=0; i< n; i++) { System.out.println("Hello, I'm "+ name); System.out.println(" I go to bed now, bye bye ... wow ... ");
} }
public static void main(String args[]){ int n = 1000; int nt = 4 ; for (int i=0; i< nt; i++){
MyThread t = new MyThread("Thread"+i,n); }
} }
VÍ DỤ 522
![Page 78: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/78.jpg)
Ưu tiên hóa thread
• Cài đặt mức độ ưu tiên phân phối CPU cho các thread.
Khi tất cả các thread đều ở trang thái ready, thread nào
có ưu tiên cao hơn được phân phối CPU trước.
• Độ ưu tiên trong Java được định nghĩa bằng các hằng số
nguyên theo thứ tự giảm dần như sau:
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
Thread.MIN_PRIORITY
23
![Page 79: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/79.jpg)
Phương thức kiểm soát ưu tiên
• setPriority( int x) : Đặt độ ưu tiên của luồng là x
• int getPriority( ) : Trả về giá trị ưu tiên của luồng
24
![Page 80: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/80.jpg)
Ví dụ 6
int prio[]= { Thread.MAX_PRIORITY,
Thread.NORM_PRIORITY,
Thread.MIN_PRIORITY};
for (int i=0; i< nt; i++){
MyThread t = new MyThread("Thread"+i,n);
t.setPriority(prio[i%3]);
25
![Page 81: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/81.jpg)
Kỹ thuật Pipe
• Giới thiệu
• Các loại pipe
• Pipe trong java
26
![Page 82: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/82.jpg)
Giới thiệu pipe• Là kỹ thuật được hỗ trợ trong hầu hết các ngôn ngữ lập
trình. Tạo cầu nối giao tiếp giữa các process
• Dữ liệu chạy trên ống dẫn theo một chiều nhất định �
một đầu để ghi data vào và một đầu để đọc data ra.
Process A
Process B
pipe
27
![Page 83: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/83.jpg)
Giới thiệu Pipe• Pipe thích hợp cho ứng dụng mà dữ liệu đầu ra của quá trình
này là đầu vào của quá trình kia.
• Pipe cũng có thể áp dụng cho giao tiếp giữa client và server
trong ứng dụng dạng client/server.
Client Server
request
reply
28
![Page 84: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/84.jpg)
Các loại pipe
• Named pipe
• Loại này có thể cho phép hai quá trình có không gian địa chỉ
khác nhau (trên cùng một máy) giao tiếp với nhau.
• Normal pipe
• Giới hạn trong phạm vi không gian địa chỉ của một quá trình
• Chỉ cho phép giao tiếp giữa quá trình cha với các quá trình con hay
giữa các quá trình con của một quá trình với nhau
29
![Page 85: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/85.jpg)
Pipe trong Java
• Java dùng normal pipe, cho phép giao tiếp giữa các
thread qua pipe.
• Hai lớp đại diện cho hai đầu của pipe
• java.io.PipedInputStream : đầu đọc
• java.io.PipedOutputStream : đầu ghi
• PipedInputStream là lớp con của InputStream nên nó có
tất cả các thuộc tính của InputStream
• PipedOutputStream là lớp con của OutputStream nên nó
có tất cả các thuộc tính của OutputStream
30
![Page 86: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/86.jpg)
Tạo ống dẫn
pipe
PipedOutputStream PipedInputStream
Nguyên tắc: tạo hai đối tượng thuộc hai lớp PipedInputStream
và PipedOutputStream; nối chúng lại
Sử dụng: ghi data vào PipedOutputStream, đọc data ra ở đầu
PipedInputStream
31
![Page 87: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/87.jpg)
Các bước thực hiện
1. Tạo đầu đọc:
PipedInputStream readId = new PipedInputStream();
2. Tạo đầu ghi:
PipedOutputStream writeId = new PipedOutputStream();
3. Nối đầu đọc với đầu ghi hay ngược lại
readId.connect(writeId);
// hoặc writeId.connect(readId);
Chú ý các phương thức khởi tạo ở trên đều phải bắt ngoại lệ
32
![Page 88: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/88.jpg)
Ví dụ 6 áp dụng
•Ứng dụng echo
• Phía Server: Chờ nhận các byte đến từ Client.
Với mỗi byte nhận được, Server gởi về đúng byte
đã nhận trở lại Client.
• Phía Client: Gởi các byte sang Server và chờ
nhận các byte gởi về từ Server.
33
![Page 89: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/89.jpg)
Phân tích thiết kế
PipedEchoClient PipedEchoServer
request
reply
cwPipe srPipe
crPipe swPipe
34
![Page 90: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/90.jpg)
Phân tích thiết kế
• Client và Server dưới dạng thread
• Dùng hai pipe để giao tiếp
• Chương trình ứng dụng gồm có ba lớp
• Lớp thực thi phía client
• Lớp thực thi phía server
• Lớp thực thi chương trình ứng dụng
35
![Page 91: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/91.jpg)
Bài tập 1
Viết chương trình mô phỏng quá trình "sản xuất -lưukho- phân phối", trong đó bộ phận sản xuất sẽ sản xuấtra một số lượng ngẫu nhiên n sản phẩm nào đó rồinhập kho. Bộ phận phân phối yêu cầu xuất kho một sốlượng ngẫu nhiên m sản phẩm nào đó từ kho.
Yêu cầu: nhập kho chỉ được chấp nhận nếu sốlượng hàng hóa đưa vào không vượt quá sức chứacủa kho, nếu không, phải chờ cho đến khi có đủ chỗtrống trong kho. Xuất kho chỉ được chấp nhận khi cònđủ hàng trong kho nếu không cũng phải chờ.
36
![Page 92: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/92.jpg)
Bài tập 2Viết chương trình ứng dụng client/server kết nối qua pipe.-Client chờ nhập ký tự, gửi sang server, chờ nhận ký tự từserver và in ra màn hình.-Client chờ nhận ký tự từ client, đổi sang dạng chữ hoa rồigửi lại cho client.Kết quả: chạy chương trình client: người dùng nhập vàomột câu bất kỳ ở dạng chữ thường rồi nhấn phím enter.Sau đó sẽ thấy hiện lại câu với các từ in hoa xuất hiện lầnlượt.
37
![Page 93: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/93.jpg)
CHƯƠNG 3LẬP TRÌNH ỨNG DỤNG MẠNG DÙNG SOCKET
1
![Page 94: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/94.jpg)
Tổng quan
Viết chương trình
• Chạy trên các hệ thống đầu cuối
• Truyền thông qua mạng
• Ví dụ web server giao tiếp với browser
Viết chương trình trên các
thiết bị mạng ngoài phạm vi
này
application
transport
network
data link
physical
application
transport
network
data link
physical
application
transport
network
data link
physical
2
![Page 95: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/95.jpg)
Mục tiêu
Socket API• Được giới thiệu trong BSD4.1 UNIX, 1981
• Được khởi tạo, sử dụng và hủy một cách tường minh bởi ứng dụng
• Mô hình client/server • Hai loại dịch vụ truyền tải qua socket API: • Datagram không bảo đảm • connection-oriented bảo đảm
Một giao tiếp cục bộtrên host, được tạo bởi
ứng dụng và được
điều khiển bởi hệ điều
hành, qua đó quá trình
ứng dụng có thểtruyền (hay nhận) đến(hay từ) quá trình khác
socket
Biết cách xây dựng một ứng dụng client/server
giao tiếp bằng socket
3
![Page 96: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/96.jpg)
Giao tiếp giữa các quá trình trên hai host khác nhau
• process truyền/nhận thông
điệp đến/từ socket của nó
• socket tương tự như cửa ra
vào
• Quá trình truyền thông điệp ra cửa
• Quá trình truyền dựa vào hạ tầng truyền tải trên phía kia của cánh cửa, thông tin được chuyển đến socket của quá trình thu
process
TCP với
buffers,
variables
socket
host hay
server
process
TCP với
buffers,
variables
socket
host hay
server
Internet
Được kiểm soát bởi
hệ điều hành
Được kiểm soát bởi
người lập trình
• API: (1) chọn giao thức truyền tải ; (2) khả năng sửa một vài thông số
4
![Page 97: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/97.jpg)
Lập trình socket với TCPSocket: Như là cửa thông giữa các quá trình ứng dụng
và giao thức truyền tải end-to-end (UDP hay TCP)
TCP service: truyền tải tin cậy các byte từ một process đến một process khác
process
TCP vớiBuffer và các biến
socket
Được kiểm soát bởingười lập trình
ứng dụng
Được kiểm soát bởi hệ điều hành
host hayserver
process
TCP với
Buffer và
các biến
socket
host hayserver
internet
Được kiểm soát bởingười lập trình ứng dụng
Được kiểm soát bởi hệ điều hành
5
![Page 98: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/98.jpg)
Lập trình socket với TCPClient phải liên lạc với server
• Trước hết quá trình trên server phải chạy
• server phải tạo socket để đón tiếp client
Client liên lạc server bằng:
• Tạo TCP socket
• Chỉ ra IP address, port number của quá trình trên server
• Khi client tạo socket: client TCP thiết lập kết nối đến server TCP
• Khi được liên hệ bởi client, , server TCP tạo socket mới để quá trình server giao tiếp với client
• Cho phép server giao tiếp với nhiều quá trình client
• Các chỉ số port được dùng để phân biệt các client
TCP cung cấp dịch vụ truyền tải có trật tự và bảo đảm giữa client và
server
Từ góc độ ứng dụng
6
![Page 99: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/99.jpg)
Tương tác giữa client socket và server socket qua TCP
wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()
create socket,port=x, for
incoming request:welcomeSocket =
ServerSocket()
create socket,connect to hostid, port=xclientSocket =
Socket()
closeconnectionSocket
read reply fromclientSocket
closeclientSocket
Server Client
send request usingclientSocketread request from
connectionSocket
write reply toconnectionSocket
TCP Thiết lập kết nối
7
![Page 100: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/100.jpg)
outT
oS
erv
er
to network from network
inF
rom
Serv
er
inF
rom
User
keyboard monitor
Process
clientSocket
inputstream
inputstream
outputstream
TCPsocket
Client
process
client TCP socket
Stream với socket
• Một input stream PHẢI
được kết với socket,
SOCKET như là một
nguồn nhập của quá trình.
• Một output stream PHẢI
được kết với socket,
SOCKET như là một đích
đến của quá trình.
8
![Page 101: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/101.jpg)
Lập trình socket với UDPUDP: không có kết nối giữa
client và server
• Không bắt tay
• sender gắn địa chỉ IP và
port của đích vào mỗi gói
• server phải tách địa chỉ IP
và port của client từ gói
nhận được
UDP: data có thể không
đúng thứ tự ở máy thu hay
mất
Từ góc độ ứng dụng
UDP cung cấp dịch vụtruyền tải không bảo đảmgiữa client và server
9
![Page 102: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/102.jpg)
Tương tác giữa client socket và server socket qua UDP
Server
closeclientSocket
read datagram fromclientSocket
create socket,
clientSocket = DatagramSocket()
Client
Create datagram with server IP andport=x; send datagram viaclientSocket
create socket,port= x.
serverSocket = DatagramSocket()
read datagram fromserverSocket
write reply toserverSocketspecifying client address,port number
10
![Page 103: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/103.jpg)
Giao tiếp qua stream
sendP
acket
to network from network
receiv
eP
acket
inF
rom
User
keyboard monitor
Process
clientSocket
UDP
packet
input
stream
UDP
packet
UDP
socket
Output: truyền
packet (UDP gửi dòng byte)
Input: nhận packet Client
process
client UDP socket
11
![Page 104: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/104.jpg)
Mô hình ứng dụng Client-Server sử dụng
Socket ở chế độ có nối kết (TCP) (1/3)
Giai đoạn 1: Server tạo Socket, gán số hiệu cổng và lắng nghe yêu cầu nối kết.
• socket(): Server yêu cầu tạo một socket để có thể sử dụng các dịch vụ
của tầng vận chuyển.
• bind(): Server yêu cầu gán số hiệu cổng (port) cho socket.
• listen(): Server lắng nghe các yêu cầu nối kết từ các client trên cổng đã được
gán.
Giai đoạn 2: Client tạo Socket, yêu cầu thiết lập một nối kết với Server
• socket(): Client yêu cầu tạo một socket để có thể sử dụng các dịch vụ của tầng
vận chuyển, thông thường hệ thống tự động gán một số hiệu cổng còn rảnh
cho socket của Client.
• connect(): Client gởi yêu cầu nối kết đến server có địa chỉ IP và Port xác định.
• accept(): Server chấp nhận nối kết của client, khi đó một kênh giao tiếp
ảo được hình thành, Client và server có thể trao đổi thông tin với nhau thông qua
kênh ảo này.
12
![Page 105: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/105.jpg)
Mô hình ứng dụng Client-Server sử dụng
Socket ở chế độ có nối kết (TCP) (2/3)
Giai đoạn 3: Trao đổi thông tin giữa Client và Server.
• Sau khi chấp nhận yêu cầu nối kết, thông thường server thực hiện lệnh
read() và nghẽn cho đến khi có thông điệp yêu cầu (Request Message) từ client
gởi đến.
• Server phân tích và thực thi yêu cầu. Kết quả sẽ được gởi về client bằng
lệnh write().
• Sau khi gởi yêu cầu bằng lệnh write(), client chờ nhận thông điệp
kết quả (ReplyMessage) từ server bằng lệnh read().
• Các câu lệnh read(), write() có thể được thưc hiện nhiều lần, tùy theo
đặc tả của giao thức truyền thông cụ thể. Các thông điệp request hay reply
cũng có định dạng tùy vào giao thức truyền thông
Giai đoạn 4: Kết thúc phiên làm việc
Kênh ảo sẽ bị xóa khi Server hoặc Client đóng socket bằng lệnh close()
13
![Page 106: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/106.jpg)
Mô hình ứng dụng Client-Server sử dụng
Socket ở chế độ có nối kết (TCP) (3/3)
14
![Page 107: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/107.jpg)
Mô hình ứng dụng Client-Server sử dụng Socket ở chế độ không nối kết (UDP)
Giai đoạn 1: Server tạo Socket - gán số hiệu cổng.
• socket(): Server yêu cầu tạo một socket để có thể sử dụng các dịch vụ của
tầng vận chuyển.
• bind(): Server yêu cầu gán số hiệu cổng cho socket.
Giai đoạn 2: Client tạo Socket.
Giai đoạn 3: Trao đổi thông tin giữa Client và Server.
15
![Page 108: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/108.jpg)
Lập trình socket với javaJava hỗ trợ lập trình mạng thông qua các lớp trong gói java.net. Một số lớp tiêu biểu được dùng cho lập trình Client-Server sử dụng socket làm phương tiện giao tiếp như: • InetAddress: Lớp này quản lý địa chỉ Internet bao gồm địa chỉ IP và tên máy tính. • Socket: Hỗ trợ các phương thức liên quan đến Socket cho chương trình Client ở chế độ có nối kết. • ServerSocket: Hỗ trợ các phương thức liên quan đến Socket cho chương trình Server ở chế độ có nối kết. • DatagramSocket: Hỗ trợ các phương thức liên quan đến Socket ở chế độ không nối kết cho cả Client và Server. • DatagramPacket: Lớp cài đặt gói tin dạng thư tín người dùng (Datagram Packet) trong giao tiếp giữa Client và Server ở chế độ không nối kết.
16
![Page 109: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/109.jpg)
Xây dựng chương trình Client ở chế độ
có nối kết
Các bước tổng quát:
1. Mở một socket nối kết đến server đã biết địa chỉ IP (hay tên
miền) và số hiệu cổng.
2. Lấy InputStream và OutputStream gán với Socket.
3. Tham khảo Protocol của dịch vụ để định dạng đúng
dữ liệu trao đổi với Server.
4. Trao đổi dữ liệu với Server nhờ vào các InputStream và
OutputStream.
5. Đóng Socket trước khi kết thúc chương trình.
17
![Page 110: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/110.jpg)
Lớp java.net.Socket (1/2)
Lớp Socket hỗ trợ các phương thức cần thiết để xây dựng cácchương trình client sử dụng socket ở chế độ có nối kếtCác phương thức:- public Socket(String HostName, int PortNumber) throws
IOException
dùng để nối kết đến một server có tên là HostName, cổng làPortNumber, kết quả là một kênh ảo được thành lập giữa client vàserver• HostName: Địa chỉ IP hoặc tên logic theo dạng tên miền.• PortNumber: có giả trị từ 0 ..65535Ví dụ:
Socket s = new Socket(“www.ptithcm.edu.vn”,80);Hoặc: Socket s = new Socket(“113.161.98.131”,80);
18
![Page 111: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/111.jpg)
Lớp java.net.Socket (2/2)- public InputStream getInputStream()
Trả về InputStream nối với Socket, chương trình Client dùng InputStream này để nhận dữ liệu từ Server gởi về.
Ví dụ: Lấy InputStream của Socket s: InputStream is = s.getInputStream();
- public OutputStream getOutputStream()
Trả về OutputStream nối với Socket. Chương trình Client dùng OutputStream này để gởi dữ liệu cho Server.
Ví dụ: Lấy OutputStream của Socket s: OutputStream os = s.getOutputStream();
- public close()
Đóng Socket lại, giải phóng kênh ảo, xóa nối kết giữa Client và Server.
19
![Page 112: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/112.jpg)
Ví dụ chương trình TCPEchoClient import java.io.*;
import java.net.Socket;
public class TCPEchoClient{
public static void main(String args[]){
try {
Socket s = new Socket(args[0],7); // Cổng echo server qui định là 7
InputStream is = s.getInputStream(); // Lấy InputStream
OutputStream os = s.getOutputStream(); // Lấy OutputStream
for (int i='0'; i<='9';i++){ // Gui ‘0’ ->’9’ den EchoServer
os.write(i); // Gởi 1 ký tự sang Server
int ch = is.read(); // Chờ nhận 1 ký tự từ Server
System.out.print((char)ch); // In ký tự nhận được ra màn hình
}
} //try
catch(IOException ie){
System.out.println("Loi: Khong tao duoc socket");
} //catch
} //main
}
20
![Page 113: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/113.jpg)
Xây dựng chương trình Server ở chế độ
có nối kết
Có hai trường hợp:
- Server phục vụ theo kiểu tuần tự
- Server phục vụ theo kiểu song song
21
![Page 114: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/114.jpg)
Lớp java.net.ServerSocket
Lớp ServerSocket hỗ trợ các phương thức cần thiết để xây dụng các chương trình Server sử dụng socket ở chế độ có nối kết. Có các phương thức quan trọng:-public ServerSocket(int PortNumber);
Tạo một Socket với số hiệu cổng là PortNumber mà sau đó Server sẽ lắng nghe trên cổng này. Ví dụ: Tạo socket cho Server với số hiệu cổng là 7:
ServerSocket ss = new ServerSocket(7); -public Socket accept()
Lắng nghe yêu cầu nối kết của các Client. Hoạt động ở chế độ nghẽn, sẽ bị nghẽn cho đến khi có một yêu cầu nối kết của client gởi đến. Khi có yêu cầu nối kết của Client gởi đến, nó sẽ chấp nhận yêu cầu nối kết, trả về một Socket là một đầu của kênh giao tiếp ảo giữa Server và Client yêu cầu nối kết. Ví dụ: Socket ss chờ nhận yêu cầu nối kết:
Socket s = ss.accept(); Server sau đó sẽ lấy InputStream và OutputStream của Socket mới s để giao tiếp với Client.
22
![Page 115: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/115.jpg)
Xây dựng chương trình Server phục vụ
tuần tự
-Tại một thời điểm Server chỉ chấp nhận một yêu cầu nối kết. Các yêu cầu nối kết của các Client khác đều không được đáp ứng.Các bước tổng quát của một Server phục vụ tuần tự 1. Tạo socket và gán số hiệu cổng cho server. 2. Lắng nghe yêu cầu nối kết. 3. Với một yêu cầu nối kết được chấp nhận thực hiện các bước sau: • Lấy InputStream và OutputStream gắn với Socket của kênh ảo vừa
được hình thành. • Lặp lại công việc sau:
� Chờ nhận các yêu cầu (công việc). � Phân tích và thực hiện yêu cầu. � Tạo thông điệp trả lời. � Gởi thông điệp trả lời về Client. � Nếu không còn yêu cầu hoặc Client kết thúc, đóng Socket và quay
lại bước 2.
23
![Page 116: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/116.jpg)
Ví dụ Chương trìnhSTCPEchoServer
import java.net.*; import java.io.*; public class STCPEchoServer {
public final static int defaultPort = 7; public static void main(String[] args) {
try { ServerSocket ss = new ServerSocket(defaultPort);
while (true) { try {
Socket s = ss.accept(); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); int ch=0; while(true) {
ch = is.read(); if(ch == -1) break; // thoát nếu kênh ảo bị xóaos.write(ch);
} s.close();
} catch (IOException e) {
System.err.println(" Connection Error: "+e); }
} } catch (IOException e) {
System.err.println(" Server Creation Error:"+e); }
} }
24
![Page 117: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/117.jpg)
Xây dựng chương trình Server phục vụ
song song- Tại một thời điểm Server chấp nhận nhiều yêu cầu nối kết và phục vụ
nhiều Client cùng lúc.- Chương trình Server phục vụ song song gồm 2 phần thực hiện song song nhau: • Phần 1: Xử lý các yêu cầu nối kết. • Phần 2: Xử lý các thông điệp yêu cầu từ khách hàng.
Phần 1: Lặp lại các công việc sau: • Lắng nghe yêu cầu kết nối của khách hàng. • Chấp nhận một yêu cầu kết nối.
� Tạo kênh giao tiếp ảo mới với khách hàng. � Tạo Phần 2 để xử lý các thông điệp yêu cầu của khách hàng.
Phần 2: Lặp lại các công việc sau: • Chờ nhận thông điệp yêu cầu của khách hàng. • Phân tích và xử lý yêu cầu. • Gởi thông điệp trả lời cho khách hàng. Ứng với mỗi client trên server có một phần 2, phần 2 kết thúc khi kênh ảo bị xóa� thiết kế theo thread, phần 1 là phân phối luôn tồn tại trên server, phần 2 là các thread công tác (worked thread)
25
![Page 118: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/118.jpg)
Ví dụ chương trình PTCPEchoServerclass RequestProcessing extends Thread {
Socket channel; //Socket của kênh ảo nối với Client hiện tại
public RequestProcessing(Socket s){
channel = s; // Nhận socket của kênh ảo nối với Client
}
public void run() {
try {
OutputStream os = channel.getOutputStream();
InputStream is = channel.getInputStream();
while (true) {
int n = is.read(); // Nhận ký tự từ Client
if (n == -1) break; // Thoát nếu kênh ảo bị xóa
os.write(n); // Gởi ký tự nhận được về Client
}
}
catch (IOException e) {
System.err.println("Request Processing Error: "+e);
}
}
}
26
![Page 119: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/119.jpg)
Ví dụ chương trình PTCPEchoServer (tt)
import java.net.*;
import java.io.*;
public class PTCPEchoServer {
public final static int defaultPort = 7; // Cổng mặc định
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(defaultPort); //Tạo socket cho server
while (true) {
try {
Socket s = ss.accept(); // Lắng nghe các yêu cầu kết nối
RequestProcessing rp = new RequestProcessing(s); // Tạo phần xử lý
rp.start(); // Khởi động phần xử lý cho Client hiện tại
}
catch (IOException e) {
System.out.println("Connection Error: "+e);
}
}
}
catch (IOException e) {
System.err.println("Create Socket Error: "+e);
}
}
}
27
![Page 120: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/120.jpg)
Xây dựng ứng dụng Client/Server ở chế
độ không nối kết
28
• Mô hình client - server sử dụng lớp ServerSocket và
Socket ở trên dùng giao thức TCP.
• Nếu muốn sử dụng mô hình client - server với giao thức UDP,
sử dụng hai lớp java.net.DatagramSocket và
java.net.DatagramPacket.
• DatagramSocket được sử dụng để truyền và nhận các
DatagramPacket.
• Dữ liệu được truyền đi là một mảng những byte, chúng được
gói vào trong lớp DatagramPacket
![Page 121: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/121.jpg)
Lớp DatagramPacket
29
-public DatagramPacket(byte[] b, int n)
Tạo ra một DatagramPacket chứa n bytes dữ liệu đầu tiên của mảng b. Trả về một đối tượng thuộc lớp DatagramPacket
Ví dụ: Tạo DatagramPacket để nhận dữ liệu: byte buff[] = new byte[60000];DatagramPacket inPacket = new Datagrampacket(buff, buff.lenth);
-public DatagramPacket(byte[] b, int n, InternetAddress ia, int port)
Tạo một DatagramPacket chứa dữ liệu và cả địa chỉ của máy nhận dữ liệuVí dụtry {//Địa chỉ Internet của máy nhận
InetAddress ia = InetAddess.getByName("www.sgu.edu.vn"); int port = 80; // Cổng của socket nhận String s = "My second UDP Packet"; // Dữ liệu gởi đi byte[] b = s.getBytes(); // Đổi chuỗi thành mảng bytes
// Tạo gói tin gởi đi DatagramPacket outPacket = new DatagramPacket(b, b.length, ia, port);
} catch (UnknownHostException e) {System.err.println(e); }
![Page 122: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/122.jpg)
Lớp DatagramPacket (tt)
30
Các phương thức lấy thông tin trên một DatagramPacket nhận được
Khi nhận được một DatagramPacket từ một quá trình khác gởi đến, ta có thể lấy
thông tin trên DatagramPacket này bằng các phương thức sau:
• public synchronized() InternetAddress getAddress() : Địa chỉ máy gởi
• public synchronized() int getPort() : Cổng của quá trình gởi
• public synchronized() byte[] getData() : Dữ liệu từ gói tin
• public synchronized() int getLength() : Chiều dài của dữ liệu trong gói tin
![Page 123: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/123.jpg)
Lớp DatagramPacket (tt)
31
Các phương thức đặt thông tin cho gói tin gởi
Trước khi gởi một DatagramPacket đi, ta có thể đặt thông tin trên DatagramPacket
này bằng các phương thức sau:
• public synchronized() void setAddress(IntermetAddress dis) : Đặt địa chỉ máy
nhận.
• public synchronized() void setPort(int port) : Đặt cổng quá trình nhận
• public synchronized() void setData(byte buffer[]) : Đặt dữ liệu gởi
• public synchronized() void setLength(int len) : Đặt chiều dài dữ liệu gởi
![Page 124: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/124.jpg)
Lớp DatagramSocket
32
public DatagramSocket() throws SocketException
• Tạo Socket kiểu không nối kết cho Client. Hệ thống tự động gán số hiệu cổng
chưa sử dụng cho socket.
• Ví dụ: Tạo một socket không nối kết cho Client:
try {
DatagramSocket ds = new DatagramSocket();
} catch(SocketException se) {
System.out.print("Create DatagramSocket Error: "+se);
}
![Page 125: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/125.jpg)
Lớp DatagramSocket (tt)
33
public DatagramSocket(int port) throws SocketException
• Tạo Socket kiểu không nối kết cho Server với số hiệu cổng được xác
định
trong tham số (port).
• Ví dụ: Tạo một socket không nối kết cho Server với số hiệu cổng là 7:
try {
DatagramSocket dp = new DatagramSocket(7);
} catch(SocketException se) {
System.out.print("Create DatagramSocket Error: "+se);
}
![Page 126: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/126.jpg)
Lớp DatagramSocket (tt)
34
public void send(DatagramPacket dp) throws IOException
• Dùng để gởi một DatagramPacket đi.
• Ví dụ: Gởi chuỗi "My second UDP Packet", cho quá trình ở địa
chỉ www.sgu.edu.vn, cổng nhận là 19:
try {
DatagramSocket ds = new DatagramSocket(); //Tạo Socket
//Địa chỉ Internet của máy nhận
InetAddress ia = InetAddess.getByName("www.sgu.edu.vn");
int port = 19; // Cổng của quá trình nhận
String s = "My second UDP Packet"; // Dữ liệu cần gởi
byte[] b = s.getBytes(); // Đổi sang mảng bytes
// Tạo gói tin
DatagramPacket outPacket = new DatagramPacket(b, b.length, ia, port);
ds.send(outPacket); // Gởi gói tin đi
}
catch (IOException e) { System.err.println(e); }
![Page 127: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/127.jpg)
Lớp DatagramSocket (tt)
35
public synchronized void receive(Datagrampacket dp) throws IOException
• Chờ nhận một DatagramPacket. Quá trình sẽ bị nghẽn cho đến khi có dữ liệu đến.
• Ví dụ:
try {
DatagramSocket ds = new DatagramSocket(); //Tạo Socket
byte[] b = new byte[60000]; // Nơi chứa dữ liệu nhận được
DatagramPacket inPacket = new DatagramPacket(b, b.length);// Tạo gói tin
ds.receive(inPacket); // Chờ nhận gói tin
}
catch (IOException e) {
System.err.println(e);
}
![Page 128: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/128.jpg)
Chương trình UDPEchoServer
36
public class UDPEchoServer {
public final static int port = 7; // Cổng mặc định của Server
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(port); // Tạo Socket với cổng là 7
byte[] buffer = new byte[6000];
while(true) { /
DatagramPacket incoming = new DatagramPacket(buffer,buffer.length);
ds.receive(incoming); // Chờ nhận gói tin gởi đến
// Lấy dữ liệu khỏi gói tin nhận và đổi từ mảng byte ra chuỗi
String theString = new String(incoming.getData(),0,incoming.getLength());
// Tạo gói tin gởi chứa dữ liệu vừa nhận được
DatagramPacket outsending = new DatagramPacket(theString.getBytes(),
incoming.getLength(),incoming.getAddress(), incoming.getPort());
ds.send(outsending);
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
![Page 129: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/129.jpg)
Chương trình
UDPEchoClient
37
public class UDPEchoClient extends Object{ public final static int serverPort = 7; // Cổng mặc định của Echo Server
public static void main(String[] args) { try {
if (args.length ==0) { // Kiểm tra tham số, là địa chỉ của Server System.out.print("Syntax: java UDPClient HostName");
return; } DatagramSocket ds = new DatagramSocket(); // Tạo DatagramSocket InetAddress server = InetAddress.getByName(args[0]); // Địa chỉ Server while(true) {
InputStreamReader isr = new InputStreamReader(System.in); // Nhập BufferedReader br = new BufferedReader(isr); // một chuỗi String theString = br.readLine(); // từ bàn phím byte[] data = theString.getBytes(); // Đổi chuỗi ra mảng bytes // Tạo gói tin gởi DatagramPacket dp = new DatagramPacket(data,data.length,server, serverPort); ds.send(dp); // Send gói tin sang Echo Server byte[] buffer = new byte[6000]; // Vùng đệm cho dữ liệu nhận // Gói tin nhận DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
ds.receive(incoming); // Chờ nhận dữ liệu từ EchoServer gởi về // Đổi dữ liệu nhận được dạng mảng bytes ra chuỗi và in ra màn hình System.out.println(new String(incoming.getData(), 0, incoming.getLength()));
} } catch (IOException e) { System.err.println(e); }
} }
![Page 130: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/130.jpg)
Bài tập
38
Bài 1. Viết lại các chương trình ví dụ ở chế độ có kết nối, sao cho có thể xuất nhập
với chuỗi.
Bài 2. Viết chương trình nhận đối số là một URL. Nối kết đến Web Server trong URL
nhận được, lấy trang web về và in ra màn hình theo dạng textfile (html).
Bài 3. Viết chương trình theo mô hình Client-Server sử dụng dụng Socket ở chế độ
có nối kết. Trong đó :
+ Server làm nhiệm vụ đọc một ký tự số từ '0' đến '9'.
( Ví dụ : nhận số 0 : trả về "khong" , 1 : trả về "một" ; ... ... 9 : trả về
"chín", nếu nhận ký tự khác số thì trả về "Không phải số nguyên" ).
+ Client sẽ nhập vào 1 ký tự, gửi qua Server, nhận kết quả trả về từ
Server và thể hiện lên màn hình
![Page 131: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/131.jpg)
LẬP TRÌNH MULTICASTNGUYỄN HỒNG SƠN
PTITHCM
![Page 132: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/132.jpg)
Multicast networking
![Page 133: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/133.jpg)
Multicast networking
• TTL - Time To Live: Số router tối đa mà một gói multicast có thể đi qua.
• Broadcast: Gửi packet đến tất cả các IP hosts trong một subnet
• Multicast: packet có thể đi ngang qua nhiều mạng
![Page 134: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/134.jpg)
MBone• MBone = Internet Multicast Backbone
• Largest deployment of multicast on the Internet
• Multicast island: network or group of adjacent networks that supports
multicast
• TCP/IP tunnelling: scheme of moving multicast packets by putting them in
regular unicast IP packets
• TTL <= 64 restricts a packet to the local multicast island
![Page 135: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/135.jpg)
Importance & limitations of multicast• Importance
• Reduce transmission traffic
• Reduce load on network servers
• Limitations
• Routers & switches need to be multicast-enabled
• Need management tools for multicast deployment
• Complete deployment of IP multicast over Internet is very difficult
• No security measures to protect multicast traffic now, e.g. cannot restrict
group joining
![Page 136: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/136.jpg)
Hệ thống Multicast
Cần hạ tầng và giao thức hỗ trợ
Một nhóm multicast được chỉ định bởi một địa chỉ IP lớp D và một UDP port.Địa chỉ IP multicast trong dải từ 224.0.0.0 đến 239.255.255.255. Tuy nhiên địa chỉ 224.0.0.0 được để lại và không nên dùng.
![Page 137: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/137.jpg)
Multicast networking protocol
• IGMP (Internet Group Management Protocol)
• IGMP được dùng bởi các host và router liền kề để thiết lập các thành viên
nhóm multicast
• IGMP quản lý thành viên của các nhóm IP multicast.
• IGMP chỉ cần cho IPv4, IPv6 được thiết kế để kiểm soát multicast một cách
trực tiếp.
![Page 138: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/138.jpg)
Multicast trong Java
• MulticastSocket là lớp con của DatagramSocket.
• Được dùng để truyền và nhận các gói IP multicast.
![Page 139: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/139.jpg)
ConstructorsMulticastSocket()
MulticastSocket(int port)
MulticastSocket(SocketAddress bindaddr)
![Page 140: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/140.jpg)
Chi tiết hàm tạo (1/3)
public MulticastSocketMulticastSocketMulticastSocketMulticastSocket() throws IOExceptionCreate a multicast socket.
• When the socket is created
the DatagramSocket.setReuseAddress(boolean) method is called to enable the
SO_REUSEADDR socket option.
Throws:
IOException - if an I/O exception occurs while creating the MulticastSocket
![Page 141: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/141.jpg)
Chi tiết hàm tạo (2/3)
public MulticastSocketMulticastSocketMulticastSocketMulticastSocket(int port) throws IOExceptionCreate a multicast socket and bind it to a specific port.
• When the socket is created the DatagramSocket.setReuseAddress(boolean)method
is called to enable the SO_REUSEADDR socket option.
Parameters:
port - port to use
Throws:
IOException - if an I/O exception occurs while creating the MulticastSocket
![Page 142: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/142.jpg)
Chi tiết hàm tạo (3/3)
public MulticastSocketMulticastSocketMulticastSocketMulticastSocket(SocketAddress bindaddr) throws IOExceptionCreate a MulticastSocket bound to the specified socket address.
Or, if the address is null, create an unbound socket.
• When the socket is created the DatagramSocket.setReuseAddress(boolean) method is
called to enable the SO_REUSEADDR socket option.
Parameters: bindaddr - Socket address to bind to, or null for an unbound socket.
Throws:
IOException - if an I/O exception occurs while creating the MulticastSocket
![Page 143: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/143.jpg)
setTimeToLive
public void setTimeToLivesetTimeToLivesetTimeToLivesetTimeToLive(int ttl) throws IOException• Set the default time-to-live for multicast packets sent out on this MulticastSocket in
order to control the scope of the multicasts.
• The ttl must be in the range 0 <= ttl <= 255 or an IllegalArgumentException will
be thrown.
Parameters:
ttl - the time-to-live
Throws:
IOException - if an I/O exception occurs while setting the default time-to-live value
![Page 144: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/144.jpg)
getTimeToLive
public int getTimeToLivegetTimeToLivegetTimeToLivegetTimeToLive() throws IOExceptionGet the default time-to-live for multicast packets sent out on the socket.
Returns:
the default time-to-live value
Throws:
IOException - if an I/O exception occurs while getting the default time-to-live value
![Page 145: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/145.jpg)
joinGroup
public void joinGroupjoinGroupjoinGroupjoinGroup(InetAddress mcastaddr) throws IOException• Joins a multicast group. Its behavior may be affected
by setInterface or setNetworkInterface..
Parameters:
mcastaddr - is the multicast address to join
Throws:
IOException- if there is an error joining or when the address is not a multicast address.
![Page 146: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/146.jpg)
Dạng khác của joinGroup
public void joinGroupjoinGroupjoinGroupjoinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException• Joins the specified multicast group at the specified interface..
Parameters:
mcastaddr - is the multicast address to join
netIf - specifies the local interface to receive multicast datagram packets, or null to defer to the
interface set by setInterface(InetAddress) or setNetworkInterface(NetworkInterface)
![Page 147: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/147.jpg)
leaveGroup
public void leaveGroupleaveGroupleaveGroupleaveGroup(InetAddress mcastaddr) throws IOException• Leave a multicast group. Its behavior may be affected
by setInterface or setNetworkInterface.
Parameters:
mcastaddr - is the multicast address to leave
Throws:
IOException - if there is an error leaving or when the address is not a multicast
address.
![Page 148: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/148.jpg)
Dạng khác của leaveGroup
public void leaveGroupleaveGroupleaveGroupleaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOExceptionLeave a multicast group on a specified local interface.
Parameters:
mcastaddr - is the multicast address to leave
netIf - specifies the local interface or null to defer to the interface set
by setInterface(InetAddress) or setNetworkInterface(NetworkInterface)Throws:
IOException - if there is an error leaving or when the address is not a multicast address.
![Page 149: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/149.jpg)
setInterface
public void setInterfacesetInterfacesetInterfacesetInterface(InetAddress inf) throws SocketExceptionSet the multicast network interface used by methods whose behavior would be affected by
the value of the network interface. Useful for multihomed hosts.
Parameters:
inf : the InetAddress
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.
![Page 150: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/150.jpg)
getInterface
public InetAddress getInterfacegetInterfacegetInterfacegetInterface() throws SocketExceptionRetrieve the address of the network interface used for multicast packets.
Returns:
An InetAddress representing the address of the network interface used for multicast
packets.
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.
![Page 151: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/151.jpg)
setNetworkInterface
public void setNetworkInterfacesetNetworkInterfacesetNetworkInterfacesetNetworkInterface(NetworkInterface netIf) throws SocketExceptionSpecify the network interface for outgoing multicast datagrams sent on this socket.
Parameters:
netIf - the interface
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.
![Page 152: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/152.jpg)
getNetworkInterfacepublic NetworkInterface getNetworkInterfacegetNetworkInterfacegetNetworkInterfacegetNetworkInterface() throws SocketExceptionGet the multicast network interface set.
Returns:
the multicast NetworkInterface currently set
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.
![Page 153: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/153.jpg)
setLoopbackMode
public void setLoopbackModesetLoopbackModesetLoopbackModesetLoopbackMode(boolean disable) throws SocketExceptionDisable/Enable local loopback of multicast datagrams
The option is used by the platform's networking code as a hint for setting
whether multicast data will be looped back to the local socket.
Because this option is a hint, applications that want to verify what loopback
mode is set to should call getLoopbackMode()Parameters:
disable - true to disable the LoopbackMode
Throws:
SocketException - if an error occurs while setting the value
![Page 154: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/154.jpg)
getLoopbackMode
public boolean getLoopbackModegetLoopbackModegetLoopbackModegetLoopbackMode() throws SocketExceptionGet the setting for local loopback of multicast datagrams.
Returns:
true if the LoopbackMode has been disabled
Throws:
SocketException - if an error occurs while getting the value
![Page 155: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/155.jpg)
send@Deprecatedpublic void sendsendsendsend(DatagramPacket p, byte ttl) throws IOExceptionSends a datagram packet to the destination, with a TTL (time- to-live) other than
the default for the socket. Its behavior may be affected by setInterface..
Parameters:
p - is the packet to be sent. The packet should contain the destination multicast ip address
and the data to be sent. One does not need to be the member of the group to send
packets to a destination multicast address.
ttl - optional time to live for multicast packet. default ttl is 1.
Throws:
IOException - is raised if an error occurs i.e error while setting ttl.
![Page 156: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/156.jpg)
Các Method thừa kế từ java.net.DatagramSocket
bind, close, connect, connect, disconnect, getBroadcast,
getChannel, getInetAddress, getLocalAddress, getLocalPort,
getLocalSocketAddress, getPort, getReceiveBufferSize,
getRemoteSocketAddress, getReuseAddress, getSendBufferSize,
getSoTimeout,
getTrafficClass, isBound, isClosed, isConnected, receive,
send, setBroadcast,setDatagramSocketImplFactory,
setReceiveBufferSize, setReuseAddress, setSendBufferSize,
setSoTimeout, setTrafficClass
![Page 157: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/157.jpg)
Lập trình multicast
•Tương tự như dùng DatagramSocket ngoại trừ:
• Khi gửi multicast packet có thể chỉ giá trị TTL
• Để nhận multicast packet trước hết phải gia nhập (join) một nhóm
multicast
•Nhiều MulticastSocket có thể lắng nghe trên cùng một port trên cùng một
máy (DatagramSocket thì không thể)
•Không thể tạo MulticastSocket trên một UDP port đang được dùng bởi một
DatagramSocket trên cùng một host
![Page 158: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/158.jpg)
Ví dụimport java.net.*;
import java.io.*;
import java.util.*;
public class DaytimeMulticastServer {
public static final int defaultPort = 1234;
public static void main (String args[]) throws Exception {
if (args.length > 1 ) throw new IllegalArgumentException
("Syntax: DaytimeMulticastServer [<multicastgroup>]");
InetAddress multicastGroup = InetAddress.getByName(
args.length==0 ? "234.5.6.7": args[0]);
MulticastSocket socket = new MulticastSocket();
// socket.joinGroup(multicastGroup);
while (true) {
Thread.sleep(5000);
System.out.println("Multicast Data ...");
String str = (new Date()).toString();
byte[] data = str.getBytes();
DatagramPacket packet = new DatagramPacket(
data, data.length, multicastGroup, defaultPort);
socket.send(packet);
}
}
}
![Page 159: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/159.jpg)
import java.net.*;
import java.io.*;
import java.util.*;
public class DaytimeMulticastClient {
public static final int defaultPort = 1234;
public static void main (String args[]) throws Exception {
if (args.length > 1 ) throw new IllegalArgumentException
("Syntax: DaytimeMulticastClient [<multicastgroup>]");
InetAddress multicastGroup = InetAddress.getByName(
args.length==0 ? "234.5.6.7": args[0]);
MulticastSocket socket = new MulticastSocket(defaultPort);
socket.joinGroup(multicastGroup);
byte[] buffer = new byte[80];
DatagramPacket packet = new DatagramPacket (buffer,
buffer.length);
socket.receive(packet);
String str = new String(packet.getData());
System.out.println("Time received from
" + packet.getAddress() + " is: " + str);
}
}
![Page 160: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/160.jpg)
Bài tập
Thiết kế và lập trình ứng dụng dịch vụ multicast như sau:
• Server đóng vai trò là trung tâm phục vụ quảng bá thông
tin cho các client. Server hoạt động theo chế độ tuần tự.
• Mỗi khi muốn quảng bá thông tin đến nhóm multicast, các
client sẽ gửi thông tin đến server và nhờ server quảng bá
đến nhóm multicast
Server
Client
Nhóm multicast
![Page 161: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/161.jpg)
CHƯƠNG 4
KÍCH HOẠT PHƯƠNG THỨC Ở XA(RMI _REMOTE METHOD INVOCATION )
1
![Page 162: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/162.jpg)
Khái niệm RPC (Remote Procedure Call)
• Cơ chế cho phép một chương trình có thể gọi thực thi
phương thức trên một máy tính khác
• Chương trình có hai loại phương thức: cục bộ và ở xa
• Khi gọi một phương thức ở xa, một thành phần của
chương trình gọi là Stub sẽ chuyển hướng để kích hoạt
một phương thức tương ứng nằm trên một máy tính khác
với máy của chương trình gọi.
• Cơ chế cho phép xây dựng ứng dụng dạng client/server
một cách đơn giản.
• Server cung cấp các phương thức kích hoạt từ xa
• Một chương trình client có thể gọi phương thức ở xa trên
nhiều máy server khác nhau.
2
![Page 163: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/163.jpg)
Kiến trúc của ứng dụng client/server theo
RPC
return call
unPack Pack
receive send
Client
ClientStub
RPCRuntime
call return
unPack Pack
receive send
Server
ServerStub
RPCRuntime
exec
wait
CallPacket
ResultPacket
3
![Page 164: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/164.jpg)
Kiến trúc của ứng dụng client/server theo
RPC (tt)• Phần ClientStub cung cấp một bộ các hàm cục bộ mà
phần Client có thể gọi. Mỗi một hàm của ClientStub đại
diện cho một hàm ở xa được cài đặt và thực thi trên
Server
• Khi một hàm của ClientStub được gọi bởi Client,
ClientStub sẽ đóng gói một packet chỉ ra phương thức ởxa tương ứng mà Client muốn thực thi cùng với các tham
số. Sau đó hệ thống RPCRuntime sẽ gởi packet này đến
phần ServerStub của Server.
4
![Page 165: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/165.jpg)
Kiến trúc của ứng dụng client/server theo
RPC
return call
unPack Pack
receive send
Client
ClientStub
RPCRuntime
call return
unPack Pack
receive send
Server
ServerStub
RPCRuntime
exec
wait
CallPacket
ResultPacket
5
![Page 166: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/166.jpg)
Kiến trúc của ứng dụng client/server theo
RPC (tt)• RPCRuntime bên phía server chuyển packet lên phần
ServerStub. ServerStub mở packet, xác định hàm ở xamà Client muốn thực hiện cùng với các tham số của nó.ServerStub gọi một thủ tục tương ứng nằm trên phầnServer
• Server cho thực thi thủ tục được yêu cầu và gởi kết quảthực thi được cho ServerStub. ServerStub đóng gói kếtquả thực trong một gói tin trả lời, chuyển cho phầnRPCRuntime cục bộ để gởi sang RPCRuntime của Client.
• ClientStub và ServerStub có thể tạo ra bằng lập trình haybằng các công cụ cung cấp bởi hệ thống
• Hầu hết các hệ điều hành mạng và ngôn ngữ lập trìnhđều hỗ trợ RPC
6
![Page 167: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/167.jpg)
Kiến trúc của ứng dụng client/server theo
RPC
return call
unPack Pack
receive send
Client
ClientStub
RPCRuntime
call return
unPack Pack
receive send
Server
ServerStub
RPCRuntime
exec
wait
CallPacket
ResultPacket
7
![Page 168: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/168.jpg)
Giới thiệu RMI
• RMI là cơ chế RPC trong ngôn ngữ lập trình Java.
• RMI cho phép một đối tượng chạy trên một máy ảo Java
này có thể kích hoạt một phương thức của một đối tượng
đang chạy trên một máy ảo Java khác.
• Đối tượng có phương thức được gọi từ xa gọi là Remote
Object.
• Ứng dụng RMI thường bao gồm 2 phần :
�Chương trình Server tạo một số các Remote Object, tạo cáctham chiếu (reference) đến chúng và chờ những chương trìnhClient kích hoạt các phương thức của các Remote Object này.
�Chương trình Client lấy một tham chiếu đến một hoặc nhiềuRemote Object trên Server và kích hoạt các phương thức từ xathông qua các tham chiếu.
8
![Page 169: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/169.jpg)
Kiến trúc của chương trình Client/Server
theo cơ chế RMI
• Stub chứa các tham chiếu đến
các phương thức ở xa trên
Server.
• Skeleton nhận các yêu cầu từ
Stub để kích hoạt phương thức
tương ứng trên Server.
• Remote Reference Layer là hệ
thống phục vụ truyền thông của
RMI.
9
![Page 170: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/170.jpg)
Các cơ chế trong một ứng dụng phân tán
• Locate remote objects: xác định cách thức mà chương
trình Client có thể lấy được tham chiếu (Stub) đến các đối
tượng ở xa, ví dụ sử dụng Naming Service lưu giữ các
tham khảo đến các đối tượng cho phép gọi từ xa để client
tìm.
• Communicate with remote objects: cơ chế giao tiếp với
đối tượng ở xa
• Load class bytecodes for objects: cơ chế tải mã
Bytecodes của các đối tượng từ máy ảo này sang máy ảo
khác.
10
![Page 171: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/171.jpg)
Hoạt động của một ứng dụng
Client/Server theo cơ chế RMI
Stub
Skeleton
Remote Object
RMIregistry
Stub Naming class
Server
Server JVM
1
2
3Server tạo ra các
đối tượng cho phép
gọi từ xa cùng với
các Stub và
Skeleton của chúng.
Server sử dụng
lớp Naming để đăng
ký tên cho một đối tượng từ xa (1)
Naming đăng ký Stub
của đối tượng từ xa vớiRegistry Server (2).
Registry Server sẵn
sàng cung cấp
tham thảo đến đối
tượng từ xa khi có yêu cầu (3)
11
![Page 172: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/172.jpg)
Hoạt động của một ứng dụng Client/Server theo cơ chế RMI (tt)
Stub
Naming class
Client
RMIregistry
Stub
Skeleton
Remote
Object
Naming
Server
Server JVMClient JVM
4
5
6
7
7
Client yêu cầu
Naming định vị đối tượng xa
qua tên đã
được đăng ký
với dịch vụ tên
(4).
Naming tải Stub của đối tượng xa
từ dịch vụ tên mà đối tượng xa đã
đăng ký về Client (5)
Cài đặt đối tượng Stub và trả về tham
khảo đối tượng xa cho Client (6)
Client thực thi một
lời gọi phương
thức xa thông qua
đối tượng Stub (7)
12
![Page 173: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/173.jpg)
Các lớp hỗ trợ chương trình Client/Server
theo RMI trong Java
• java.rmi.Naming
• java.rmi.RMISecurityManager
• java.rmi.RemoteException;
• java.rmi.server.RemoteObject
• java.rmi.server.RemoteServer
• java.rmi. server.UnicastRemoteObject
13
![Page 174: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/174.jpg)
Các bước xây dựng ứng dụng phân tán
với RMI
1. Thiết kế và lập trình các thành phần của ứng dụng.
2. Biên dịch các chương trình nguồn và tạo ra Stub và
Skeleton.
3. Tạo các lớp cần thiết có thể truy xuất từ mạng.
4. Khởi động ứng dụng
14
![Page 175: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/175.jpg)
Thiết kế và lập trình các thành phần của
ứng dụng
Xác định lớp nào là lớp cục bộ, lớp nào là lớp được gọi từxa
• Định nghĩa các giao diện cho các phương thức ở xa (remoteinterfaces): Khai báo các phương thức có thể được kích hoạt từxa bởi các Client; Xác định các lớp cục bộ làm tham số hay giá trịtrả về của các phương thức được gọi từ xa
• Lập trình các đối tượng từ xa (remote objects): Lập trình cho cácphương thức được gọi từ xa đã được khai báo trong RemoteInterface và có thể định nghĩa và lập trình cho cả các phương thứcđược sử dụng cục bộ
• Lập trình các chương trình Client: Các chương trình Client màsẽ sử dụng các Remote Object có thể được lập trình sau khi cácRemote Interface đã được định nghĩa.
15
![Page 176: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/176.jpg)
Biên dịch các chương trình nguồn và tạo
ra Stub và Skeleton• Bước thứ nhất: dùng chương trình biên dịch javac để
biên dịch các tập tin nguồn như các remote interface,
các lớp của remote interface, lớp server, lớp client và
các lớp liên quan khác
• Bước thứ hai: dùng trình biên dịch rmic để tạo ra stub và
skeleton cho các đối tượng từ xa từ các lớp của remote
interface
16
![Page 177: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/177.jpg)
Tạo các lớp cần thiết có thể truy xuất từ
mạng• Tạo nơi chứa các file có liên quan như remote interface
stub, các lớp hỗ trợ khác cần thiết phải tải về Client. Tổchức sao cho có thể truy cập tập tin này thông qua một
Web server
17
![Page 178: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/178.jpg)
Khởi động ứng dụng
• Khởi động rmiregistry server
• Khởi động server
• Thực thi client
18
![Page 179: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/179.jpg)
Các công việc cụ thể để tạo ứng dụng RMI
• Viết khai báo các phương thức được gọi từ xa của đối
tượng. (giao diện (interface))
• Viết lớp cho giao diện đã được khai báo.
• Viết chương trình Server.
• Viết chương trình Client.
• Dịch các tập tin nguồn theo dạng RMI để tạo ra các lớp tương
ứng và stub cho client, skeleton cho server.
• Khởi động dịch vụ registry.
• Thực hiện chương trình Server.
• Thực thi chương trình Client.
19
![Page 180: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/180.jpg)
Ví dụ minh họa
• Ứng dụng HelloWorld: Định nghĩa phương thức kích hoạt
từ xa sayHello(). Mỗi khi client gọi phương thức này nó sẽ
trả về chuỗi HelloWorld.
• Trình tự thực hiện qua các bước sau:
20
![Page 181: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/181.jpg)
Bước 1: Khai báo các phương thức được
gọi từ xa của đối tượng (remote interface)
Syntax tổng quát:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface InterfaceName extends Remote {
ReturnType remoteMethodOne() throws RemoteException;
ReturnType remoteMethodTwo() throws RemoteException;
. . .
}
21
![Page 182: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/182.jpg)
• Định nghĩa remote interface có tên là HelloItf, có
phương thức được gọi từ xa là String sayHello()
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloItf extends Remote {
String sayHello() throws RemoteException;
}
22
![Page 183: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/183.jpg)
Bước 2: Tạo lớp cho giao diện đã được
khai báo• Syntax tổng quát:
import java.rmi. server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class RemoteClass extends UnicastRemoteObject implements
InterfaceName {
public RemoteClass() throws RemoteException {
super();
....... // Implement of Method
}
public ReturnType remoteMethodOne() throws RemoteException {
....... // Implement of Method
}
public ReturnType remoteMethodTwo() throws RemoteException {
....... // Definition of Method
}
}
23
![Page 184: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/184.jpg)
• Định nghĩa lớp có tên là Hello
import java.rmi. server.UnicastRemoteObject; import java.rmi.RemoteException; public class Hello extends UnicastRemoteObject implements HelloItf {
public Hello() throws RemoteException { super();
} public String sayHello() {
return "Hello World !"; }
}
24
![Page 185: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/185.jpg)
Bước 03: Viết chương trình Server• Syntax tổng quát:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
public class ServerName {
public static void main(String args[]) {
if (System.getSecurityManager() == null) { // Cài đặt cơ chế bảo mật
System.setSecurityManager(new RMISecurityManager());
}
try {
// Tạo các đối tượng từ xa
RemoteClass remoteObject = new RemoteClass();
// Đăng ký tên cho các đối tượng từ xa
Naming.rebind(“RegistryName", remoteObject);
...
}
catch (Exception e) { System.out.println(”Error: . . .” + e);
}
}
}
25
![Page 186: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/186.jpg)
• Tạo server có tên HelloServer chứa một đối tượng từ xa obj thuộc lớp Hello. Đăng ký tên cho đối tượng obj là HelloObject
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
public class HelloServer {
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
Hello obj = new Hello();
Naming.rebind("HelloObject", obj);
System.out.println("HelloObject is registried");
}
catch (Exception e) {
System.out.println("Error: " + e);
} }}
26
![Page 187: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/187.jpg)
Bước 04: Viết chương trình Client• Syntax tổng quát:
import java.rmi.Naming;
import java.rmi.RemoteException;
public class Client {
public static void main(String args[]) {
String remoteObjectURL = "rmi://NameServer/RegistryName”;
Interfacename object = null;
try {
object = (InterfaceName)Naming.lookup(remoteObjectURL);
object.remoteMethodOne();
...
}
catch (Exception e) {
System.out.println(" Error: ”+ e);
}
}
}
27
![Page 188: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/188.jpg)
• Tạo client có tên là HelloClient, tìm đối tượng HelloObject trên
rmiregistry chẳng hạn tại địa chỉ 192.168.1.12. Gọi phương thức
sayHello() và in kết quả trả về ra màn hình
import java.rmi.Naming;
import java.rmi.RemoteException;
public class HelloClient {
public static void main(String args[]) {
String helloURL = "rmi://192.168.1.12/HelloObject";
HelloItf object = null;
try {
object = (HelloItf)Naming.lookup(helloURL);
String message = object.sayHello();
System.out.println(message);
}
catch (Exception e) {
System.out.println("Client Error :" + e);
}
}
}
28
![Page 189: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/189.jpg)
Bước 05: Dịch các tập tin nguồn theo dạng RMI để tạo ra các lớp
tương ứng và stub cho client, skeleton cho server
• Syntax:
javac InterfaceName.java RemoteClass.java Server.java Client.java
rmic RemoteClass
Thực hiện biên dịch các lớp
javac Hello.java HelloItf.java HelloServer.java HelloClient.java
rmic Hello.class
29
![Page 190: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/190.jpg)
Bước 06: Khởi động dịch vụ rmiregistry
• Syntax:
start rmiregistry [port]
(Default port=1099)
30
![Page 191: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/191.jpg)
Bước 07: Thực hiện chương trình Server
• Syntax :
java -Djava.security.policy =UrlOfPolicyFile ServerName
Trong đó UrlOfpolicyFile là địa chỉ nơi lưu tập tin qui định chính
sách bảo mật. Tùy vào chính sách mà nội dung tập tin sẽ thay đổi.
Để minh họa ở đây sẽ tạo tập tin policy.java cho phép tất cả đều
được phép truy xuất tập tin từ server như sau:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
31
![Page 192: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/192.jpg)
Bước 08: Thực thi chương trình Client
• Syntax:
java ClientName
• Thực thi HelloClient với địa chỉ của rmiregistry đưa vào trong tham số
>java HelloClient localhost
32
![Page 193: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/193.jpg)
Bài tập
• Xây dựng ứng dụng tài khoản ngân hàng:
- Tạo các đối tượng tài khoản khả dụng để client kết nối
đến, sau đó client có thể thao tác với các đối tượng này
bằng cách kích hoạt các phương thức của chúng
- Các biến và phương thức liên quan một tài khoản cá
nhân sẽ được đóng gói trong lớp ứng dụng gọi là Account.
Lớp Account có các phương thức lấy tên (getName), số tài
khoản (getNum), số dư (getBalance), rút tiền (withdraw),
nộp tiền (deposit).
33
![Page 194: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/194.jpg)
CHƯƠNG 5
KẾT NỐI CƠ SỞ DỮ LIỆU
![Page 195: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/195.jpg)
Nội dung
Tổng quan về ODBC & JDBC
Tạo lập JDBC trên JAVA
Cách thức truy nhập và điều khiển JDBC
![Page 196: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/196.jpg)
Tổng quan
• Các chương trình được viết trong Java có thể giao tiếp
với các cơ sở dữ liệu quan hệ (cục bộ hay từ xa) qua
Java Database Connectivity (JDBC) API
• Vendor Variation Problem: Làm sao kiểm soát nhiều định
dạng khác nhau trong cơ sở dữ liệu của các nhà cung
cấp khác nhau.
![Page 197: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/197.jpg)
• Microsoft đã phát triển Open Database Connectivity như
chuẩn cho các ứng dụng Windows để kết nối và dùng
Microsoft databases.
• ODBC được thiết kế trong Windows, liên kết chặt chẽ với
Microsoft databases
• JDBC đưa ra một số giải pháp kết nối database, thực sự
là một chuẩn kết nối cơ sở dữ liệu như ODBC.
![Page 198: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/198.jpg)
• Để dùng JDBC truy xuất data từ một loại cơ sở dữ liệu đặc biệt
nào đó, cần cung cấp vài phần mềm cho phép JDBC giao tiếp
với API của nhà cung cấp cơ sở dữ liệu này. Các phần mềm
như vậy thường được gọi là driver.
• Thông tin về JDBC drivers cho các database có thể tham khảo
tại: http://servlet.java.sun.com/products/jdbc/drivers
• ODBC driver chỉ khả dụng cho Microsoft (MS) databases, các
nhà cung cấp khác đã có giải pháp đem ODBC cho các non-
MS databases. Sun cung cấp JDBC-ODBC bridge driver trong
gói sun.jdbc.odbc
![Page 199: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/199.jpg)
![Page 200: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/200.jpg)
• JDBC-ODBC bridge driver chuyển đổi giao thức JDBC
sang ODBC tương ứng và cho phép các lập trình viên
java truy xuất cơ sở dữ liệu có ODBC drivers
![Page 201: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/201.jpg)
SQL và các phiên bản JDBC
• Phương tiện chuẩn để truy xuất cơ sở dữ liệu quan hệ là
SQL. Trong JDBC API có gói java.sql
• JDBC đầu tiên trong JDK 1.1 là JDBC 1.0
• JDK 1.2 (J2SE 1.2) có JDBC 2.0
• Với J2SE 1.2.2 có JDBC 2.1
• JDBC 3.0 được cung cấp vào 2002
• Phiên bản được dùng phổ biến nhất là JDBC 2
![Page 202: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/202.jpg)
Tạo một ODBC Data Source
• Trước khi có thể truy xuất một ODBC-driven database
qua một chương trình java, cần phải đăng ký database
như một ODBC Data Source
• database có thể được tham chiếu bởi tên Data Source
Name (DSN)
• Giả sử database đã được tạo, các bước cần đề xây
dựng một ODBC Data Source như sau:
![Page 203: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/203.jpg)
• 1. Using the mouse, select Start Control Panel from the startup menu.
• 2. Double-click Administrative Tools.
• 3. Double-click Data Sources (ODBC) to display the ODBC Data Source
• Administrator window.
• 4. Ensure that the User DSN tab is selected.
• 5. Click on the Add... button to display the Create New Data Source
• window.
• 6. Select Microsoft Access Driver (*.mdb) and click on Finish.
• 7. To locate the required database within the directory structure, click on the
• Select... button.
• 8. Navigate the directory structure and select the required database.
• 9. Supply a (meaningful) name for the data source. (The 'Description' field is
• optional.)
• 10. If specifying a username and password (not mandatory and not necessary
• for the examples in this section), select Advanced Options and then key in
• the values, clicking on OK when finished.
• 11. Click on OK to finish registration.
![Page 204: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/204.jpg)
Truy xuất Database đơn giản
• Connection, Statement và ResultSet objects. Các tên
này tham chiếu như interfaces
• JDBC driver phải cài đặt ba interfaces này và cài đặt các
class để tạo object sau đó.
![Page 205: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/205.jpg)
• Dùng JDBC để truy xuất một database yêu cầu các bước:
1. Nạp database driver.
2. Thiết lập một kết nối đến database.
3. Dùng kết nối để tạo một Statement object và lưu một tham chiếu đến
đối tượng này.
4. Dùng tham chiếu Statement ở trên để chạy một truy vấn đặc biệt hay
update statement và chấp nhận result.
5. Thao tác và hiển thị các results hay kiểm tra và hiển thị số dòng
database bị ảnh hưởng (cho cập nhật).
6. Lặp lại các bước 4 và 5 nhiều lần khi cần cho truy vấn/cập nhật.
7. Đóng kết nối.
![Page 206: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/206.jpg)
Database ví dụ
• Giả sử đã có một MS Access database được gọi là
Finances.mdb chứa một bảng gọi là Accounts. Cấu trúc
của bảng như sau
• Giả sử DSN của database này là Finances.
![Page 207: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/207.jpg)
Bước 1: Nạp Database Driver
• Điều này được thực hiện qua phương thức tỉnh (static)
forName của lớp Class:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
![Page 208: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/208.jpg)
Bước 2: Thiết lập kết nối đến Database
• Khai báo một Connection reference và gọi static method
getConnection của lớp DriverManager để trả về một
Connection object cho reference này. Phương thức
getConnection lấy ba tham số String:
• Một URL-style address cho database;
• Một user name;
• Một password.
• JDBC API đề nghị địa chỉ của database có dạng như sau:
jdbc:<sub-protocol>:<data-source>
<sub-protocol> chỉ dịch vụ kết nối database (một driver)
![Page 209: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/209.jpg)
• <data-source> cung cấp tất cả thông tin cần thiết bởi service để định vị database
(cụ thể là URL path đến database)
• Đối với một local ODBC database với data source name Finances, sub-protocol
là odbc và phần sau cùng của địa chỉ đơn giản là tên của data source:
jdbc:odbc:Finances
• Giả sử Finances database là local và chúng ta không cài user name hay
password cho database này, dòng yêu cầu để mở một kết nối đến database sẽ là:
Connection link =
DriverManager.getConnection(
"jdbc:odbc:Finances", "", "");
![Page 210: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/210.jpg)
• Nếu database này là ở xa, dòng trên được viết lại:
Connection link =
DriverManager.getConnection(
"jdbc:odbc://AnyServer.SomethingElse.com/Finances",
"", "");
![Page 211: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/211.jpg)
Bước 3: Tạo một Statement object và lưu
một tham chiếu đến đối tượng này
Một đối tượng Statement được tạo bằng cách gọi
phương thức createStatement của đối tượng
Connection.
Địa chỉ của đối tượng trả về bởi lời gọi phương thức này
được lưu trong tham chiếu Statement. Trong dòng code
sau tham chiếu này được gọi đơn giản là statement.
Statement statement = link.createStatement();
![Page 212: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/212.jpg)
Bước 4: Chạy một truy vấn đặc biệt hay
update statement và chấp nhận result
-Class Statement có các phương thức executeQuery và
executeUpdate được dùng để thực thi hai loại này. Phương
thức đầu trả về một đối tượng ResultSet, phương thức thứ
hai trả về một số nguyên chỉ số hàng trong database bị ảnh
hưởng bởi cập nhật.
-Trên thực tế thường lưu SQL query dưới dạng biến String
và sau đó yêu cầu executeQuery với biến này như một
tham số. Xem ví dụ sau:
![Page 213: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/213.jpg)
Ví dụ(i) String selectAll = "SELECT * FROM Accounts";
ResultSet results =
statement.executeQuery(selectAll);
(ii) String selectFields =
"SELECT acctNum, balance FROM Accounts";
ResultSet results =
statement.executeQuery(selectFields);
(iii) String selectRange = "SELECT * FROM Accounts"
+ " WHERE balance >= 0"
+ " AND balance <= 1000"
+ " ORDER BY balance DESC";
ResultSet results =
statement.executeQuery(selectRange);
(iv) String selectNames =
"SELECT * FROM Accounts WHERE surname < Jones'";
ResultSet results =
statement.executeQuery(selectNames);
![Page 214: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/214.jpg)
Bước 5: Thao tác và hiển thị các results hay kiểm tra
và hiển thị số dòng database bị ảnh hưởng
-Đối tượng ResultSet được trả về khi đáp ứng lời gọi
phương thức executeQuery chứa các hàng của database
thỏa mãn tiêu chuẩn tìm kiếm của truy vấn. ResultSet
interface chứa nhiều phương thức để thao tác các hàng
này.
-Có thể chuyển đến hàng đặc biệt bằng bất kỳ các
phương thức nói trên, có thể thu thập data theo tên trường
hay vị trí trường. Dùng phương thức getXXX thích hợp
(trong đó XXX biểu thị cho kiểu Java thích hợp)
![Page 215: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/215.jpg)
Ví dụ
• int getInt (String <columnName>)
• int getInt (int <columnIndex>)
• String getString (String <columnName>)
• String getString (int <columnIndex>)
![Page 216: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/216.jpg)
Chương trìnhimport java.sql.*;
public class JDBCSelect
{
private static Connection link;
private static Statement statement;
private static ResultSet results;
//Alternatively, the above 3 variables may
//be declared non-static within main, but
//must then be initialised explicitly to null.
public static void main(String[] args)
{
try
{
//Step 1...
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Step 2...
link = DriverManager.getConnection(
"jdbc:odbc:Finances","","");
}
catch(ClassNotFoundException cnfEx)
{
System.out.println(
![Page 217: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/217.jpg)
"* Unable to load driver! *"); System.exit(1);
} //For any of a number of reasons, it may not be //possible to establish a connection... catch(SQLException sqlEx) {
System.out.println( "* Cannot connect to database! *");
System.exit(1); } try {
//Step 3... statement = link.createStatement(); String select = "SELECT * FROM Accounts"; //Step 4... results = statement.executeQuery(select);
} catch(SQLException sqlEx) {
System.out.println( "* Cannot execute query! *");
sqlEx.printStackTrace(); System.exit(1);
}
![Page 218: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/218.jpg)
try
{
System.out.println();
//Step 5...
while (results.next())
{
System.out.println("Account no. "
+ results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3)
+ " "
+ results.getString(2));
System.out.printf("Balance: %.2f %n%n"
+ results.getFloat(4));
}
}
catch(SQLException sqlEx)
![Page 219: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/219.jpg)
{
System.out.println(
"* Error retrieving data! *");
sqlEx.printStackTrace();
System.exit(1);
}
//(No further queries, so no Step 6!)
try
{
//Step 7...
link.close();
}
catch(SQLException sqlEx)
{
System.out.println(
"* Unable to disconnect! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
}
![Page 220: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/220.jpg)
LÀM VIỆC VỚI URL
CHƯƠNG 6
![Page 221: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/221.jpg)
Tạo một URL
In Java program, you can use a String containing this text to create a URL
object:
URL myURL = new URL("http://example.com/");
![Page 222: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/222.jpg)
Tạo một URL liên hệ với URL khácA relative URL contains only enough information to reach the resource relative
to (or in the context of) another URL.
Relative URL specifications are often used within HTML files.
Within page, are links to other pages
In Java programs, can create a URL object from a relative URL specification
http://example.com/pages/page1.html http://example.com/pages/page2.html
URL myURL = new URL("http://example.com/pages/"); URL page1URL = new URL(myURL, "page1.html"); URL page2URL = new URL(myURL, "page2.html");
Create URL objects for these pages relative to their common base URL:
http://example.com/pages/
![Page 223: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/223.jpg)
URL ConstructorsCreate a URL object from another URL object (the base) and a relative URL
specification
URL(URL baseURL, String relativeURL)
new URL("http", "example.com", "/pages/page1.html");
new URL("http://example.com/pages/page1.html");
URL gamelan = new URL("http", "example.com", 80, "pages/page1.html");
![Page 224: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/224.jpg)
Địa chỉ URL có ký tự đặc biệtSome URL addresses contain special characters, for example the space
character
http://example.com/hello world/
To make these characters legal they need to be encoded before passing
them to the URL constructorURI uri = new URI("http", "example.com", "/hello world/", "");URL url = uri.toURL();
![Page 225: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/225.jpg)
MalformedURLException
try { URL myURL = new URL(...); } catch (MalformedURLException e) {
// exception handler code here // ...}
Each of the four URL constructors throws a MalformedURLException if the
arguments to the constructor refer to a null or unknown protocol
![Page 226: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/226.jpg)
Trích thông tin từ một URLGet the protocol, authority, host name, port number, path, query, filename, and reference from a
URL using these accessor methods:
getProtocolReturns the protocol identifier component of the URL.
getAuthorityReturns the authority component of the URL.
getHostReturns the host name component of the URL.
getPortReturns the port number component of the URL. The getPort method returns an integer that is
the port number. If the port is not set, getPort returns -1.
getPathReturns the path component of this URL.
getQueryReturns the query component of this URL.
getFileReturns the filename component of the URL. The getFile method returns the same as getPath,
plus the concatenation of the value of getQuery, if any.
getRefReturns the reference component of the URL.
![Page 227: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/227.jpg)
Ví dụ1import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL("http://example.com:80/docs/books/tutorial" + "/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority()); System.out.println("host = " + aURL.getHost()); System.out.println("port = " + aURL.getPort()); System.out.println("path = " + aURL.getPath()); System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " + aURL.getFile()); System.out.println("ref = " + aURL.getRef());
} }
![Page 228: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/228.jpg)
Đọc trực tiếp từ URL
create a URL call the URL's openStream() method
returns a java.io.InputStream object
reading from a URL is as easy as reading
from an input stream.
![Page 229: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/229.jpg)
Ví dụ 2
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL fit_ptithcm = new URL("http://fit.ptithcm.edu.vn/");
BufferedReader in = new BufferedReader(
new InputStreamReader(fit_ptithcm.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
![Page 230: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/230.jpg)
Kết nối với một URL
create a URL objectcall the URL object's
openConnection method
get a URLConnection
object
use this URLConnection object to setup
parameters and general request
properties before connecting.
Connection to the remote object
represented by the URL is only initiated
when the URLConnection.connect
method is called
Client
program
URL
![Page 231: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/231.jpg)
Ví dụ 3
try {
URL myURL = new URL("http://hcm.ptit.edu.vn/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
![Page 232: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/232.jpg)
Đọc từ một URL connection
explicitly retrieves a URLConnection object
gets an input stream from the connection
creates a BufferedReader on the input
stream
reads from the BufferedReader
![Page 233: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/233.jpg)
Ví dụ 4
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL fit = new URL("http://fit.ptithcm.edu.vn/");
URLConnection yc = fit.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
![Page 234: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/234.jpg)
Ghi vào một URL connectionHTML pages contain forms — text fields and other GUI objects that let you
enter data to send to the server
Make a java program to interact with a server-side process:
Create a URL.
Retrieve the URLConnection object.
Set output capability on the URLConnection.
Open a connection to the resource.
Get an output stream from the connection
Write to the output stream. Close the output stream.
![Page 235: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/235.jpg)
Ví dụ 5import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
![Page 236: Bài giảng Lập trình mạng](https://reader030.vdocuments.pub/reader030/viewer/2022020715/5872c5211a28ab0c718b6095/html5/thumbnails/236.jpg)
Bài tập
• Bài 1. Viết chương trình nhận đối số là một URL, tải nội
dung trang web về và in ra màn hình theo dạng textfile.
• Bào 2. Viết ứng dụng calculator giao tiếp qua URL