Transcript
Page 1: Bai Thuc Hanh Lap Trinh Phan Tan

- 1-

Bộ môn Mạng, Khoa CNTT - 2005

MỤC LỤC

Bài 1 LẬP TRÌNH PHÂN TÁN ĐỐI TƯỢNG JAVA RMI................... 2 1.1. Chương trình RMI Hello ............................................................................. 2

1.1.1. Cài đặt lớp giao diện HelloInterface.java ........................................... 2 1.1.2. Cài đặt lớp hiện thực HelloImpl.java.................................................. 2 1.1.3. Cài đặt chương trình Server : HelloServer.java.................................. 2 1.1.4. Cài đặt chương trình Client : HelloClient .java .................................. 3 1.1.5. Biên dịch chương trình ....................................................................... 3

1.2. Chương trình RMI truy xuất cơ sở dữ liệu từ xa ......................................... 5 1.2.1. Xây dựng cơ sở dữ liệu....................................................................... 5 1.2.2. Xây dựng lớp DBServerInterface.java................................................ 5 1.2.3. Xây dựng lớp DBServerImpl.java ...................................................... 5 1.2.4. Xây dựng lớp DBServer.java.............................................................. 6 1.2.5. Xây dựng lớp DBClient.java .............................................................. 7

1.3. Chương trình minh họa kỹ thuật gọi ngược (callback) trên RMI................ 7 1.3.1. Xây dựng lớp AtServerInterface.java ................................................. 7 1.3.2. Xây dựng lớp AtServerImpl.java........................................................ 7 1.3.3. Xây dựng chương trình AtClientInterface.java .................................. 8 1.3.4. Xây dựng chương trình AtClientImpl.java ......................................... 8 1.3.5. Xây dựng chương trình Server.java ................................................... 8 1.3.6. Chương trình Client.java..................................................................... 8

Bài 2 LẬP TRÌNH PHÂN TÁN ĐỐI TƯỢNG CORBA ...................... 11 2.1. Chương trình CORBA Hello ..................................................................... 11

2.1.1. Bước 1 : Đặc tả đối tượng bằng ngôn ngữ CORBA IDL ................. 11 2.1.2. Bước 2 : Xây dựng đối tượng Hello bằng ngôn ngữ Java ................ 11 2.1.3. Bước 3 : Cài đặt đối tượng CORBA Hello ....................................... 11 2.1.4. Bước 4 : Xây dựng chương trình Server........................................... 11 2.1.5. Bước 5 : Xây dựng chương trình Client ........................................... 12 2.1.6. Chạy chương trình ............................................................................ 13

Page 2: Bai Thuc Hanh Lap Trinh Phan Tan

- 2-

Bộ môn Mạng, Khoa CNTT - 2005

Bài 1 LẬP TRÌNH PHÂN TÁN ĐỐI TƯỢNG JAVA RMI

1.1. Chương trình RMI Hello

- Xây dựng chương trình JavaRMI, client gởi yêu cầu add(x,y), sub(x,y) đến Server. Server thực hiện và trả kết quả về cho client.

1.1.1. Cài đặt lớp giao diện HelloInterface.java /* Buoc 1 : Dac ta giao tiep cho lop doi tuong o xa

*/

import java.rmi.*;

public interface HelloInterface extends java.rmi.Remote {

public String sayHello() throws java.rmi.RemoteException;

public int addItem(int x, int y) throws java.rmi.RemoteException;

public int subItem(int x, int y) throws java.rmi.RemoteException;

}//class

1.1.2. Cài đặt lớp hiện thực HelloImpl.java

- Cài đặt chi tiết các phương thức được mô tả trong lớp giao diện. /* Buoc 2 : Cai dat chi tiet phuong thuc tu xa

*/

import java.rmi.*;

public class HelloImpl implements HelloInterface {

public String sayHello() throws java.rmi.RemoteException {

System.out.println("Client da su dung phuong thuc 1 cua Server");

return "Hello World";

}//sayHello()

public int addItem(int x, int y) throws java.rmi.RemoteException {

return (x+y);

}//addItem()

public int subItem(int x, int y) throws java.rmi.RemoteException {

return (x-y);

}//subItem()

}//class

1.1.3. Cài đặt chương trình Server : HelloServer.java /* Buoc 3 : Khoi tao doi tuong giao tiep tren may chu

*/

import java.rmi.*;

import java.rmi.server.*;

public class HelloServer {

public static void main (String args[]) throws java.lang.Exception {

//Kien tao doi tuong

try {

//Kien tao doi tuong

HelloImpl obj = new HelloImpl();

Page 3: Bai Thuc Hanh Lap Trinh Phan Tan

- 3-

Bộ môn Mạng, Khoa CNTT - 2005

//Khai bao doi tuong voi may ao JVM

java.rmi.server.UnicastRemoteObject.exportObject(obj);

System.out.println("* Dang ky doi tuong");

java.rmi.Naming.bind("rmi://127.0.0.1/HelloImpl",obj);

System.out.println("* Dang ky doi tuong cho phep truy xuat tu xa : HelloImpl");

System.out.println("* Cho Client truy xuat . . .");

}catch (java.lang.Exception ex){System.out.println(ex);}

}//main

}//class

Chú ý : có thể gộp chương trình HelloRMIServer.java và HelloImplement.java vào 1 chương trình nhưng phức tạp.

1.1.4. Cài đặt chương trình Client : HelloClient .java /* Buoc 4 : Chuong trinh goi doi tuong tu xa

*/

import java.rmi.*;

public class HelloClient {

public static void main (String[] args) {

int x = 5;

int y = 3;

try {

//Tim tham chieu cua doi tuong

System.out.println("Dang tim doi tuong ...");

HelloInterface obj=(HelloInterface)java.rmi.Naming.lookup("rmi://"+ args[0] +"/HelloImpl");

//Trieu goi cac phuong thuc xu ly cua doi tuong tu xa

System.out.println(obj.sayHello());

System.out.println("* Tong = " + obj.addItem(x,y));

System.out.println("* Hieu = " + obj.subItem(x,y));

} catch (java.lang.Exception ex){System.out.println(ex); }

}

}

1.1.5. Biên dịch chương trình

• Tập tin Compiler ECHO OFF

Echo ----------------------------------------------------

Echo CHUONG TRINH COMPILE

Echo ----------------------------------------------------

Path=C:\jdk1.4\bin

Echo -----------Dich cac tap tin *.java ---------

del *.class

javac *.java

Echo -----Tao tap tin trung gian _Stub va _Skel cho doi tuong ---------

rmic HelloImplement

Pause

Page 4: Bai Thuc Hanh Lap Trinh Phan Tan

- 4-

Bộ môn Mạng, Khoa CNTT - 2005

• Tập tin Client.bat ECHO OFF

Echo ----------------------------------------------------

Echo CHUONG TRINH RMI CLIENT

Echo ----------------------------------------------------

Path=C:\jdk1.4\bin

set CLASSPATH=.;%CLASSPATH%;

java HelloRMIClient 127.0.0.1

Pause

• Tập tin Server.bat ECHO OFF

Echo ----------------------------------------------------

Echo CHUONG TRINH RMI SERVER

Echo ----------------------------------------------------

Path=C:\jdk1.4\bin

set CLASSPATH=.;%CLASSPATH%;

Echo -----------Chay chuong trinh RMIRegistry -----------

rmiregistry

Echo -----------Chay chuong trinh Server dang ky doi tuong -----------

java HelloRMIServer 127.0.0.1

Pause

• Tổ chức các chương trình CLIENT SERVER

HelloRMIClient.class

HelloInterface.class

HelloImplement_STUB.class

HelloRMIServer.class

HelloImplement_SKEL.class

• Thứ tự chạy chương trình :

1. Compiler.bat

2. Serber.bat

3. Client.bat

Page 5: Bai Thuc Hanh Lap Trinh Phan Tan

- 5-

Bộ môn Mạng, Khoa CNTT - 2005

1.2. Chương trình RMI truy xuất cơ sở dữ liệu từ xa

1.2.1. Xây dựng cơ sở dữ liệu

1.2.2. Xây dựng lớp DBServerInterface.java import java.rmi.*;

public interface DBServerInterface extends Remote {

public String queryDataBase() throws RemoteException;

}

1.2.3. Xây dựng lớp DBServerImpl.java import java.sql.*;

import java.rmi.*;

import java.io.*;

public class DBServerImpl implements DBServerInterface {

public DBServerImpl() { }

//----------------------------------------------------

public String queryDataBase() throws RemoteException {

return accessDB();

}

//----------------------------------------------------

public String accessDB() {

String stResult=" ";

Page 6: Bai Thuc Hanh Lap Trinh Phan Tan

- 6-

Bộ môn Mạng, Khoa CNTT - 2005

try {

//init database

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection connection = DriverManager.getConnection("jdbc:odbc:TAIKHOAN");

Statement statement= connection.createStatement();

boolean hasResult = statement.execute("SELECT * FROM USER");

if (hasResult) {

ResultSet rs= statement.getResultSet();

if (rs != null)

stResult= formatResult(rs);

} else

System.out.println("Khong tim duoc CSDL");

connection.close();

} catch(Exception ex)

{

System.out.println(ex.toString());

}

return stResult;

}

//------------------------------------------------------------

public String formatResult(ResultSet r) throws SQLException

{

ResultSetMetaData rmeta= r.getMetaData();

int numColumns = rmeta.getColumnCount();

String text=" ";

for(int i=1;i<= numColumns; ++i){

if (i<numColumns)

text += rmeta.getColumnName(i) + "|";

else text += rmeta.getColumnName(i);

}

text += "\n";

while (r.next()){

for(int i=1; i<=numColumns;++i){

if(i<numColumns)

text += r.getString(i)+" | ";

else

text += r.getString(i).trim();

}

text +="\n";

}

return text;

}

}//class

1.2.4. Xây dựng lớp DBServer.java import java.rmi.*;

import java.rmi.server.*;

public class DBServer {

Page 7: Bai Thuc Hanh Lap Trinh Phan Tan

- 7-

Bộ môn Mạng, Khoa CNTT - 2005

public static void main(String args[]) throws Exception {

DBServerImpl data = new DBServerImpl();

UnicastRemoteObject.exportObject(data);

Naming.bind("rmi://" + args[0] + "/myDatabase",data);

System.out.println("Waiting for Client request:");

}

}

1.2.5. Xây dựng lớp DBClient.java import java.rmi.*;

import java.sql.*;

import java.rmi.server.*;

public class DBClient {

static String result;

//----------Method main--------------------

public static void main(String args[]) throws Exception {

try {

DBServerInterface objDB =

(DBServerInterface)Naming.lookup("rmi://" + args[0] + "/myDatabase");

result = objDB.queryDataBase();

}

catch(Exception e) {

System.out.println("Error Find!"+e.toString());

}

System.out.println(result);

}

} //-------Ket thuc CT Client----------------

1.3. Chương trình minh họa kỹ thuật gọi ngược (callback) trên RMI

1.3.1. Xây dựng lớp AtServerInterface.java import java.rmi.*;

public interface AtServerInterface extends Remote {

public void registerClient(AtClientInterface c) throws java.rmi.RemoteException;

public void callServerMethod(String message) throws java.rmi.RemoteException;

}

1.3.2. Xây dựng lớp AtServerImpl.java import java.rmi.*;

import java.io.*;

public class AtServerImpl implements AtServerInterface {

AtClientInterface client;

public void registerClient(AtClientInterface client) throws java.rmi.RemoteException

{

this.client=client;

}

public void callServerMethod(String msg) throws java.rmi.RemoteException

{

Page 8: Bai Thuc Hanh Lap Trinh Phan Tan

- 8-

Bộ môn Mạng, Khoa CNTT - 2005

System.out.println(msg);

for (int i=1; i<10; i++){

String st= "Server response "+ Math.random()*1000;

client.callClientMethod(st);

}//for

}

}//class

1.3.3. Xây dựng chương trình AtClientInterface.java import java.rmi.*;

public interface AtClientInterface extends java.rmi.Remote {

public void callClientMethod(String msg) throws java.rmi.RemoteException;

}

1.3.4. Xây dựng chương trình AtClientImpl.java import java.rmi.*;

public class AtClientImpl implements AtClientInterface {

public void callClientMethod(String msg) throws java.rmi.RemoteException

{

System.out.println(msg);

}

}

1.3.5. Xây dựng chương trình Server.java import java.rmi.*;

import java.rmi.server.*;

public class Server {

public static void main (String args[]) throws java.lang.Exception {

AtServerInterface server=new AtServerImpl();

java.rmi.server.UnicastRemoteObject.exportObject(server);

java.rmi.Naming.bind("rmi://127.0.0.1/serverobject",server);

System.out.println("Waiting for client request ...");

}

}

1.3.6. Chương trình Client.java import java.rmi.*;

import java.rmi.server.*;

public class Client {

public static void main (String args[]) throws java.lang.Exception {

AtClientInterface client=new AtClientImpl();

java.rmi.server.UnicastRemoteObject.exportObject(client);

AtServerInterface server=(AtServerInterface)java.rmi.Naming.lookup("rmi://" + args[0] + "/serverobject");

// Dang ky doi tuong client voi RMI Registry

server.registerClient(client);

server.callServerMethod("Client contact Server");

}//main

Page 9: Bai Thuc Hanh Lap Trinh Phan Tan

- 9-

Bộ môn Mạng, Khoa CNTT - 2005

}//class

------------------------------------------------------------------------

Page 10: Bai Thuc Hanh Lap Trinh Phan Tan

- 10-

Bộ môn Mạng, Khoa CNTT - 2005

BÀI TẬP

1. Xây dựng chương trình Client ở dạng giao diện đồ họa, cho phép nhập vào 2 giá trị x,y trên textbox. Thực hiện gửi dữ liệu đến Server và nhận kết quả tính toán, hiển thị tại Client.

2. Xây dựng chương trình RMIClient dùng phương thức invoke() để triệu gọi đối tượng từ xa.

3. Viết chương trình RMI gồm Client, Server sử dụng các kỹ thuật truy cập CSDL và kỹ thuật gọi ngược, trong đó :

- Các Client đăng nhập vào Server theo tài khoản

- Server lưu chỉ số ID của các Client

- Server phân chia các công việc xử lý cho các Client có tên trong danh sách đã đăng ký

- Client xử lý và trả kết quả về Server

- Server tổng hợp và hiển thị kết quả.

Page 11: Bai Thuc Hanh Lap Trinh Phan Tan

- 11-

Bộ môn Mạng, Khoa CNTT - 2005

Bài 2 LẬP TRÌNH PHÂN TÁN ĐỐI TƯỢNG CORBA

2.1. Chương trình CORBA Hello

Xây dựng chương trình Hello minh họa các bước thực hiện một chương trình CORBA đơn giản, Client sẽ gọi đối tượng phân tán trên Server. Đối tượng CORBA trên Server sẽ trả về chuỗi thông báo.cho Client.

2.1.1. Bước 1 : Đặc tả đối tượng bằng ngôn ngữ CORBA IDL

(Interface Description Language)

• File Hello.idl

interface Hello {

string sayHello();

};

2.1.2. Bước 2 : Xây dựng đối tượng Hello bằng ngôn ngữ Java

Sử dụng chương trình idlj.exe để chuyển đặc tả của CORBA sang ngôn ngữ Java

Chuyển đặc tả đối tượng CORBA sang ngôn ngữ Java cho Server idlj -fserver -OldImplBase Hello.idl

Chuyển đặc tả đối tượng CORBA sang ngôn ngữ Java cho Client idlj -fclient Hello.idl

Kết quả được các file sau : HelloOperations.java

Hello.java

_HelloImplBase.java

HelloHelper.java

HelloHolder.java

_HelloStub.java

2.1.3. Bước 3 : Cài đặt đối tượng CORBA Hello

• File HelloImpl.java public class HelloImpl extends _HelloImplBase {

public String sayHello(){

System.out.println("Hello world !");

return "Hello CORBA";

}

}//class

2.1.4. Bước 4 : Xây dựng chương trình Server

• File Server.java import org.omg.CORBA.*; // All CORBA applications need these classes.

import org.omg.CosNaming.*; // Client will use the naming service

Page 12: Bai Thuc Hanh Lap Trinh Phan Tan

- 12-

Bộ môn Mạng, Khoa CNTT - 2005

import org.omg.CosNaming.NamingContextPackage.*;

public class Server {

public static void main(String args[]) throws java.lang.Exception{

System.out.println("Setup CORBA Hello Object");

// Create and initialize the ORB

org.omg.CORBA.ORB orb=org.omg.CORBA.ORB.init(args,null);

// Tao doi tuong CORBA

HelloImpl corba= new HelloImpl();

// Ket noi doi tuong CORBA voi trinh moi gioi ORB

orb.connect(corba);

// Get the root naming context

org.omg.CORBA.Object nameService =

orb.resolve_initial_references("NameService");

NamingContext nsContext =NamingContextHelper.narrow(nameService);

//Tao ten cho doi tuong

NameComponent nc=new NameComponent("Hello","");

// Resolve the object reference in naming

NameComponent path[]={nc};

//Dang ky doi tuong theo ten do dich vu tnameserv quan ly

nsContext.rebind(path,corba);

System.out.println("Waiting for client ...");

//Tao doi tuong Java

java.lang.Object obj = new java.lang.Object();

//Thuc hien lap vo tan - cho nhan yeu cau tu client

synchronized (obj){

obj.wait();

}

}//main

}//class

2.1.5. Bước 5 : Xây dựng chương trình Client

• File Client.java import org.omg.CORBA.*;

import org.omg.CosNaming.*;

public class Client{

public static void main(String args[]) throws java.lang.Exception{

//Khoi dong trinh moi gioi ORB

org.omg.CORBA.ORB orb=org.omg.CORBA.ORB.init(args,null);

// Get a reference to the object

org.omg.CORBA.Object nameService=

orb.resolve_initial_references("NameService");

//Chuyen tham chieu ve doi tuong NamingContext

NamingContext nsContext = NamingContextHelper.narrow(nameService);

//tao duong dan mang ten doi tuong

NameComponent nc=new NameComponent("Hello","");

NameComponent path[]={nc};

//Lay ve tham chieu cua doi tuong CORBA tren may chu dua vao ten

Page 13: Bai Thuc Hanh Lap Trinh Phan Tan

- 13-

Bộ môn Mạng, Khoa CNTT - 2005

Hello corba=HelloHelper.narrow(nsContext.resolve(path));

System.out.println(corba.sayHello() );

}//main

}//class

2.1.6. Chạy chương trình

• Biên dịch chương trình nguồn Path=c:\j2sdh.1.4.2\bin

javac *.java

• Chạy chương trình dịch vụ quản lý tên tnameserv.exe của CORBA có tên nameService

tnameserv -ORBInitialPort 2005

• Chạy chương trình Server java Server -ORBInitialPort 2005 -ORBInitialHost 127.0.0.1

• Chạy chương trình Client java Client -ORBInitialPort 2005 -ORBInitialHost 127.0.0.1

BÀI TẬP

Xây dựng chương trình CORBA Client bằng các ngôn ngữ như C++, Visual Basic, Delphi để truy xuất đến đối tượng phân tán trên chương trình CORBA Server (Server.java) ở trên.