Lập trình mạng bằng ngôn ngữ Java

Các khái niệm liên quan đến lập trình mạng:  Mạng máy tính  Ports  Sockets và Ports  Mô hình Client – Server  Socket Programming

pdf45 trang | Chia sẻ: lylyngoc | Lượt xem: 1627 | Lượt tải: 2download
Bạn đang xem trước 20 trang tài liệu Lập trình mạng bằng ngôn ngữ Java, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giáo viên: Dương Khai Phong Email: khaiphong@gmail.com Lý thuyết: 45 tiết Thực hành: 30 tiết Nội dung môn học Tổng quan lập trình java 1 Lập trình hướng đối tượng 2 Lập trình giao diện đồ họa 3 Lập trình mạng cơ bản 4 Ôn tập 5 www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin LẬP TRÌNH MẠNG CĂN BẢN www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin D B C A Giới thiệu lập trình mạng Các lớp hỗ trợ lập trình mạng Socket TCP Socket Programming UDP Socket Programming E Remote Method Invocation (RMI) www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: LẬP TRÌNH MẠNG CĂN BẢN A  Các khái niệm liên quan đến lập trình mạng:  Mạng máy tính  Ports  Sockets và Ports  Mô hình Client – Server  Socket Programming www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: LẬP TRÌNH MẠNG CĂN BẢN A  Các khái niệm liên quan đến lập trình mạng:  Mạng máy tính  Ports  Sockets và Ports  Mô hình Client – Server  Socket Programming www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính:  Mạng máy tính là tập hợp các máy tính hoặc các thiết bị được nối với nhau bởi các đường truyền vật lý và theo một kiến trúc nào đó.  Mạng máy tính  Tầng ứng dụng  Standard apps • HTTP • FTP • Telnet  User apps  Tầng vận chuyển  TCP  UDP  Programming Interface: • Sockets  Tầng mạng  IP  Tầng kết nối  Device drivers www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính:  Mạng máy tính Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)  TCP (Tranmission Control Protocol) là giao thức vận chuyển dựa trên kết nối logic trực tiếp giữa 2 máy tính.  Ví dụ:  HTTP  FTP  Telnet www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính:  Mạng máy tính Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)  UDP (User Datagram Protocol) là giao thức vận chuyển phi kết nối thực hiện gửi các packets gọi là datagrams từ máy này sang máy khác.  Ví dụ:  Clock server  Ping www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Ports:  TCP và UDP sử dụng port để xác định chương trình sẽ nhận dữ liệu khi đến 1 máy tính.  Mạng máy tính  Ports server P o r t Client TCP TCP or UDP port port port port app app app app port# data Data Packet www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Ports:  Port là 1 con số nguyên  Một số port đã được dành riêng cho các dịch vụ mạng phổ biến:  ftp 21/tcp  telnet 23/tcp  smtp 25/tcp  login 513/tcp  Nên dùng giá trị lớn hơn 1024  Mạng máy tính  Ports www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính  Ports  Sockets và Ports message agreed port any port socket socket Internet address = 138.37.88.249 Internet address = 138.37.94.248 other ports client server www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính  Ports  Sockets và Ports  Mô hinh Client và Server Network a client, a server, and network Client Client machine Server Server machine www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Giới thiệu lập trình mạng: TỔNG QUAN LẬP TRÌNH JAVA A  Mạng máy tính  Ports  Sockets và Ports  Mô hinh Client và Server  Socket Programming  Socket :  Điểm giao tiếp giữa máy tính và mạng  Được dùng để gửi và nhận dữ liệu  Được hỗ trợ bỡi nhiều hệ thống và ngôn ngữ lập trình  Phân loại: Server (passive) socket, client (active) socket và UDP socket logical connection sockets (end points) B www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Các lớp hỗ trợ lập trình mạng Socket: TỔNG QUAN LẬP TRÌNH JAVA  Gói java.net chứa tất cả các lớp cần thiết cho việc lập trình mạng (Java Sockets Programming)  Cú pháp khai báo: import java.net.*;  Các lớp cơ bản trong gói java.net:  InetAddress  Socket  ServerSocket  DatagramSocket  DatagramPacket B www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Các lớp hỗ trợ lập trình mạng Socket: TỔNG QUAN LẬP TRÌNH JAVA  Lớp InetAddress:  Công dụng:  Biểu diễn một địa chỉ Internet, các địa chỉ IP trong một ứng dụng mạng sử dụng Java.  Lớp này được sử dụng bởi hầu hết các lớp mạng, bao gồm Socket, ServerSocket, URL, DatagramSocket, DatagramPacket,…  Cú pháp sử dụng:  Sử dụng phương thức static để tạo ra đối tượng InetAddress.  getByName(String host)  getAllByName(String host)  getLocalHost() Ví dụ: InetAddress x = InetAddress.getByName("www.uit.edu.vn");  Ném ra biệt lệ UnknownHostException B www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Các lớp hỗ trợ lập trình mạng Socket: TỔNG QUAN LẬP TRÌNH JAVA  Ví dụ: viết chương trình truy xuất địa chỉ IP import java.net.InetAddress; import java.net.UnknownHostException; public class net_lookup { public static void main(String[] args) { String hostname=args[0]; try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } } } C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Các đối tượng cơ bản trong lập trình mạng TCP Socket  Server sockets • Chờ kết nối từ mạng • Tạo ra từ lớp java.net.ServerSocket  Client sockets • Dùng để gửi và nhận dữ liệu • Tạo ra từ lớp java.net.Socket server socket connection request client socket C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Tạo và sử dụng Server Socket server socket connection request client socket Type Description  Constructors ServerSocket(int port) khởi tạo đối tượng  Methods accept() chờ yêu cầu kết nối và tạo socket close() dừng việc chờ yêu cầu kết nối B www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Các lớp hỗ trợ lập trình mạng Socket: TỔNG QUAN LẬP TRÌNH JAVA  Ví dụ: tạo ServerSocket try { ServerSocket server = new ServerSocket(8888); while (true) { Socket incoming = server.accept(); // obtain a client socket // handle client request by reading from and writing to the socket … } } catch (IOException e) { // handle exception on creating a server socket } C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Tạo và sử dụng Client Socket Type Description  Tạo client sockets Phía client:  Socket(String host, int port) Phía server:  accept() của lớp ServerSocket khởi tạo đối tượng  Methods getInputStream() trả về InputStream để nhận dữ liệu getOutputStream() trả về OutputStream để gửi dữ liệu close() đóng kết nối C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Mô hình truyền / nhận dữ liệu giữa Server và Client: ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream Client Server Có thể là tên máy C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Ví dụ 1: viết chương trình cho server nhận thông tin là một chuỗi ký tự từ phía client gởi lên và chuyển đổi chuỗi này sang chữ hoa và gởi trả về lại cho phía client dùng phương thức TCP Socket Server (running on hostid) create socket, port=x, for incoming request: welcomeSocket = ServerSocket() read request from connectionSocket write reply to connectionSocket close connectionSocket Client wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket,connect to hostid, port=x clientSocket = Socket() send request clientSocket read reply from clientSocket close clientSocket TCP connection setup C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myserver{ public static void main(String args[]) { try{ //1. creating a server socket ServerSocket sk = new ServerSocket(6789,10); //2. Wait for connection System.out.println("Waiting for connection"); Socket s = sk.accept(); System.out.println("Connection received from " + s.getInetAddress().getHostName()); //3. get Input and Output streams PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); > //4: Closing connection in.close();out.close();sk.close(); } catch(IOException ioException){ ioException.printStackTrace();} } } TCP_MYSERVER.JAVA C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myserver{ public static void main(String args[]) { try{ //1. creating a server socket ServerSocket sk = new ServerSocket(6789,10); //2. Wait for connection System.out.println("Waiting for connection"); Socket s = sk.accept(); System.out.println("Connection received from " + s.getInetAddress().getHostName()); //3. get Input and Output streams PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); > //4: Closing connection in.close();out.close();sk.close(); } catch(IOException ioException){ ioException.printStackTrace();} } } // Process in/out data from client String message; // get data from client message = in.readLine(); System.out.println(" "+message); // send data to client out.print(message.toUpperCase()); out.flush(); // flush data to client TCP_MYSERVER.JAVA C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myclient{ public static void main(String args[]) {try{ //1. creating a socket to connect to the server Socket s = new Socket("localhost", 6789); System.out.println("Connected to localhost in port 6789"); //2. get Input and Output streams PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); //3: Communicating with the server > //4: Closing connection in.close(); out.close(); s.close(); } catch(UnknownHostException unknownHost){ System.err.println("You are trying to connect to an unknown host!"); } catch(IOException ioException){ ioException.printStackTrace();} } } TCP_MYCLIENT.JAVA C www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin TCP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myclient{ public static void main(String args[]) {try{ //1. creating a socket to connect to the server Socket s = new Socket("localhost", 6789); System.out.println("Connected to localhost in port 6789"); //2. get Input and Output streams PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); //3: Communicating with the server > //4: Closing connection in.close(); out.close(); s.close(); } catch(UnknownHostException unknownHost){ System.err.println("You are trying to connect to an unknown host!"); } catch(IOException ioException){ ioException.printStackTrace();} } } // Process in/out data from server // send data to server String message = "hello server"; out.println(message); out.flush(); // flush data to server // get data from server message = in.readLine(); System.out.println(" "+message); TCP_MYCLIENT.JAVA D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  UDP  Phi kết nối và không tin cậy.  Không đảm bảo bảo toàn dữ liệu  Socket Programming với UDP  Không cần socket làm server.  Không có luồng dữ liệu gắn vào các socket.  sending hosts đóng gói dữ liệu, IP và port thành packet rồi gửi lên mạng.  receiving host nhận packet và rút trích ra thông tin.  Các lớp cơ bản lập trình UDP  DatagramSocket: tạo kết nối mạng  DatagramPacket: để đóng gói datagram thành packet truyển trên mạng  dùng để nhận và gửi (Chứa nội dung cần gửi và địa chỉ máy gửi, port) D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA Type Description  Constructors Ném ra biệt lệ SocketException và SecurityException DatagramSocket() khởi tạo đối tượng DatagramSocket(int port) DatagramSocket(int port, InetAddress a);  Methods void connect(InetAddress, int port); close() void receive(DatagramPacket p); void send(DatagramPacket p);  Tạo và sử dụng DatagramSocket D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA Type Description  Constructors DatagramPacket( byte[] buf, int len); nhận dữ liệu DatagramPacket( byte[] buf, int len, InetAddress a, int port); gởi dữ liệu  Methods byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort();  Tạo và sử dụng DatagramPacket D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA  Ví dụ 1: viết chương trình cho server nhận thông tin là một chuỗi ký tự từ phía client gởi lên và chuyển đổi chuỗi này sang chữ hoa và gởi trả về lại cho phía client dùng phương thức UDP Socket D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myserver{ public static void main(String args[]) { try{ byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; // 1. Khởi tạo đối tượng DatagramSocket serverSocket = new DatagramSocket(9876); System.out.println("Dang cho ket noi tu client"); // 2. Nhận dữ liệu gởi từ client DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String( receivePacket.getData()); System.out.println(": " + sentence); > // 3. Gởi dữ liệu về client InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); serverSocket.close();}} catch(IOException ioException){ ioException.printStackTrace();} }} UDP_MYSERVER.JAVA D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myserver{ public static void main(String args[]) { try{ byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; // 1. Khởi tạo đối tượng DatagramSocket serverSocket = new DatagramSocket(9876); System.out.println("Dang cho ket noi tu client"); // 2. Nhận dữ liệu gởi từ client DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String( receivePacket.getData()); System.out.println(": " + sentence); > // 3. Gởi dữ liệu về client InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); serverSocket.close();} catch(IOException ioException){ ioException.printStackTrace();} }} UDP_MYSERVER.JAVA // Xử lý dữ liệu đã nhận String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); D www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin UDP Socket Programming: TỔNG QUAN LẬP TRÌNH JAVA import java.io.*; import java.net.*; public class tcp_myserver{ public static void main(String args[]) { try{ byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; // 1. Khởi tạo đối tượng DatagramSocket clientSocket = new DatagramSocket(9876); InetAddress IPAddress = InetAddress.getByName("localhost"); // 2. Gởi dữ liệu đến server BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); System.out.print(": "); String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); // 3. Nhận dữ liệu gởi về từ server DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println(": " + modifiedSentence); // 4. Đóng kết nối clientSocket.close(); } catch(UnknownHostException e){ e.printStackTrace();} catch(IOException e){e.printStackTrace();} } UDP_MYCLIENT.JAVA E www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Remote Method Invocation (RMI): TỔNG QUAN LẬP TRÌNH JAVA  RMI vs Socket programming:  Với socket programming, phải tự tạo kết nối và quản lý quá trình truyền nhận dữ liệu.  Phương pháp này phức tạp và dễ gây ra lỗi.  JVM tạo kết nối và quản lý quá trình truyền nhận dữ liệu.  Distributed programming model  Cho phép một đối tượng (local objects) có thể sử dụng các đối tượng trên máy khác (remote objects) giống như là đang chạy trên cùng 1 máy. E www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Remote Method Invocation (RMI): TỔNG QUAN LẬP TRÌNH JAVA Kiến trúc RMI Transport Remote Reference Layer Stub Skeleton Client Server Object Reference Remote Object RMI System Client JVM Server JVM JAVA PROGRAM REMOTE OBJECT REMOTE METHOD INVOCATION E www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Remote Method Invocation (RMI): TỔNG QUAN LẬP TRÌNH JAVA  Local và Remote Objects:  Local objects • Các đối tượng nằm trên local hosts  Remote objects • Các đối tượng có thể truy cập từ remote hosts • Các thể hiện của lớp này phải cài đặt interface java.rmi.Remote  Property of remote objects • Tương tự như local objects (arguments, downcasting, instanceof, etc) • Truy cập thông qua Stub E www.sites.google.com/site/khaiphong ĐH Công nghệ Thông tin Remote Method Invocation (RMI): TỔNG QUAN