Bài giảng Tổng quan lập trình Java - Lập trình mạng căn bản
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
Remote Method Invocation (RMI)
Tóm tắt nội dung Bài giảng Tổng quan lập trình Java - Lập trình mạng căn bản, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
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 LẬP TRÌNH JAVA
Định vị Remote Objects:
RMI registry
• Directory service ánh xạ RMI objects thành các tên tương ứng.
• Server: đăng ký và và pubic remote object cho các client
• Client: tìm remote object bằng các tra trong RMI registry
thông qua giao thức rmi, e.g., rmi://host:port/name
• Sử dụng lớp java.rmi.Naming
Method Description
bind(name, obj) Bind obj to name
rebind(name, obj) Bind obj to name even if already bound
unbind(name) Remove the binding
lookup(url) Return object bound to url
list(url) Return a list of all bindings
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
Thi hành một phương thức trong RMI
marshalling unmarshalling
Phương thức gọi thi hành có dạng sau:
boolean somemethod(object x, object 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
RMI – Các bước thực hiện (1)
Bước 01: Tạo giao diện (interface) khai báo các phương thức
đựợc gọi từ xa của đối tượng.
Bước 02: Tạo lớp cài đặt (class implement) cho giao diện đã
được khai báo.
Bước 03: Viết chương trình Server.
Bước 04: Viết chương trình Client.
Bước 05: Dịch các tập tin nguồn theo dạng RMI (rmic) để tạo
ra các lớp tương ứng và stub cho client, skeleton cho server.
Bước 06: Khởi động dịch vụ (rmiregistry)
Bước 07: Thực thi chương trình Server.
Bước 08: Thực thi chương trình Client
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
Ví dụ 1: viết chương trình cho phép client thực hiện gọi các
phương thức từ xa ở phía server để chuyển đổi một chuỗi chữ
thường sang một chuỗi chữ hoa và in ra dùng phương thức RMI
Các bước thực hiện:
Bước 1: Tạo giao diện (interface) MessageInterface khai báo các phương
thức đựợc gọi từ xa của đối tượng
import java.rmi.*;
public interface MessageInterface extends Remote{
String receiveMessage(String message) throws RemoteException;
void printMessageAtServer(String message) throws RemoteException;
}
MessageInterface.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
Các bước thực hiện:
Bước 2+3: cài đặt (class implement) cho giao diện MessageInterface đã
được khai báo và viết chương trình Server
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
Các bước thực hiện:
Bước 2+3: cài đặt (class implement) cho giao diện MessageInterface đã
được khai báo và viết chương trình Server
import java.rmi.*;import java.rmi.registry.*;
import java.rmi.server.*;import java.net.*;
public class rmi_server extends java.rmi.server.UnicastRemoteObject implements
MessageInterface{
String address;
Registry registry;
>
public rmi_server() throws RemoteException{
try{ address = (InetAddress.getLocalHost()).toString();}
catch(Exception e){ System.out.println("can't get inet address.");}
int port=6789;
System.out.println("this address=" + address + ",port=" + port);
try{registry = LocateRegistry.createRegistry(port);
registry.rebind("remote_Methods", this);}
catch(RemoteException e){System.out.println("remote exception"+ e);}
}
public static void main(String args[]){
try{ rmi_server server = new rmi_server();}
catch (Exception e){e.printStackTrace();System.exit(1);
}}}
RMI_MYSERVER.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
Các bước thực hiện:
Bước 2+3: cài đặt (class implement) cho giao diện MessageInterface đã
được khai báo và viết chương trình Server
import java.rmi.*;import java.rmi.registry.*;
import java.rmi.server.*;import java.net.*;
public class rmi_server extends java.rmi.server.UnicastRemoteObject implements
MessageInterface{
String address;
Registry registry;
>
public rmi_server() throws RemoteException{
try{ address = (InetAddress.getLocalHost()).toString();}
catch(Exception e){ System.out.println("can't get inet address.");}
int port=6789;
System.out.println("this address=" + address + ",port=" + port);
try{registry = LocateRegistry.createRegistry(port);
registry.rebind("remote_Methods", this);}
catch(RemoteException e){System.out.println("remote exception"+ e);}
}
public static void main(String args[]){
try{ rmi_server server = new rmi_server();}
catch (Exception e){e.printStackTrace();System.exit(1);
}}}
RMI_MYSERVER.JAVA
// Cài đặt (class implement) cho giao diện MessageInterface
public String receiveMessage(String message) throws RemoteException{
return message.toUpperCase();
}
public void printMessageAtServer(String message) throwsRemoteException{
System.out.println(" :"+message);
}
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
Các bước thực hiện:
Bước 2+3: cài đặt (class implement) cho giao diện MessageInterface đã
được khai báo và viết chương trình Server
import java.rmi.*;import java.rmi.registry.*;
import java.net.*;
public class rmi_client {
public static void main(String[] args) {
MessageInterface rmiServer;
Registry registry;
String serverAddress = "localhost"; // Địa chỉ IP máy Server
int serverPort = 6789;
String text="Xin chao";
System.out.println("sending " + text + " to " +serverAddress + ":" + serverPort);
try{
registry=LocateRegistry.getRegistry(serverAddress, serverPort);
rmiServer=(MessageInterface)(registry.lookup("remote_Methods"));
rmiServer.printMessageAtServer(text); // gọi phương thức từ xa
System.out.print(rmiServer.receiveMessage(text));
}
catch(RemoteException e){e.printStackTrace();}
catch(NotBoundException e){System.err.println(e);}
}}
RMI_MYCLIENT.JAVA
File đính kèm:
Bài giảng Tổng quan lập trình Java - Lập trình mạng căn bản.pdf

