Các bước tạo ứng dụng với RMI
Ở đây chúng ta có 1 ví dụ tạo ứng dụng máy chủ tính toán các phép tính cơ bản(+, -, *, /)
Ở phía server:
Tạo thư mục MyCalcServer, lưu các lớp sau vào đó
1> Tạo interface
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface CalculatorInterface extends Remote {
long Add(long a,long b)throws RemoteException;
long Sub(long a,long b)throws RemoteException;
long Mul(long a,long b)throws RemoteException;
float Div(float a,float b)throws RemoteException;
}
2>Tạo lớp implements cài đặt các dịch vụ ở phía máy chủ:
import java.rmi.*;
import java.rmi.server.*;
public class CalculatorImpl extends UnicastRemoteObject implements CalculatorInterface {
private ServerUI ui;
public CalculatorImpl() throws RemoteException
{
}
public CalculatorImpl(ServerUI ui) throws RemoteException
{
this.ui=ui;
}
public long Add(long a, long b) throws RemoteException {
ui.addItem(“Call from client: “+a+”+”+b+”=”+(a+b));
return a+b;
}
public long Sub(long a, long b) throws RemoteException {
ui.addItem(“Call from client: “+a+”-”+b+”=”+(a-b));
return a-b;
}
public long Mul(long a, long b) throws RemoteException {
ui.addItem(“Call from client: “+a+”*”+b+”=”+(a*b));
return a*b;
}
public float Div(float a, float b) throws RemoteException {
if(Math.abs(b-0)<0.000001)
{
ui.addItem(“Call from client: Divide by zero”);
throw new ArithmeticException();
}
ui.addItem(“Call from client: “+a+”/”+b+”=”+(a/b));
return a/b;
}
}
3>Cài đặt server. Ở đây tôi thiết kế server dùng GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
import javax.naming.Context;
import javax.naming.InitialContext;
public class ServerUI extends JFrame implements ActionListener{
private DefaultListModel dlm;
private JList lst;
private JLabel lblMessage;
private JButton btnStart,btnStop,btnExit;
private Context ctx=null;
public ServerUI(){
super(“Server RMI”);
lst=new JList(dlm=new DefaultListModel());
this.add(new JScrollPane(lst),BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,300);
JPanel pB=new JPanel(new GridLayout(2,1));
JPanel pF=new JPanel();
pB.add(pF);
pF.add(btnStart=new JButton(“Start”));
pF.add(btnStop=new JButton(“Stop”));btnStop.setEnabled(false);
pF.add(btnExit=new JButton(“Exit”));
pB.add(lblMessage=new JLabel());
btnStart.addActionListener(this);
btnStop.addActionListener(this);
btnExit.addActionListener(this);
this.add(pB,BorderLayout.SOUTH);
}
public void DislplayInfos(String msg){
lblMessage.setText(msg);
}
public void addItem(String item){
dlm.addElement(item);
}
public static void main(String[]args){
try{
ServerUI ui=new ServerUI();
java.rmi.registry.LocateRegistry.createRegistry(1099);
ui.DislplayInfos(“server is stop…”);
ui.setVisible(true);
}catch(Exception x){
x.printStackTrace();
}
}
public void actionPerformed(ActionEvent e){
Object o=e.getSource();
if(o.equals(btnStart)){
new Thread(new Runnable(){
public void run(){
try {
CalculatorInterface calc=null;
calc=new CalculatorImpl(ServerUI.this);
ctx =new InitialContext();
ctx.rebind(“rmi:calc”, calc);
lblMessage.setText(“Calculator server is running…”);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
btnStop.setEnabled(true);
btnStart.setEnabled(false);
}
else if(o.equals(btnStop)){
try {
ctx.unbind(“rmi:calc”);
ctx=null;
btnStop.setEnabled(false);
btnStart.setEnabled(true);
lblMessage.setText(“Calculator server is stopped…”);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
else if(o.equals(btnExit)){
System.exit(1);
}
}
}
4>Biên dịch:
Trong command promt, gõ dòng lệnh sau để biên dịch (thư mục hiện hành là MyCalcServer)
javac *.java
5> Thực thi:
Tạo file MyCalSVR.bat với nội dung sau
java ServerUI
//=========================================================
//=========================================================
//=========================================================
Ở phía client
Tạo thư mục MyCalcClient. Các lớp sau được lưu trong đó
1> Copy tâp tin CalculatorInterface.class vào thư mục này.
2>Tạo client như sau, ở đây chúng ta dùng GUI để thiết kế
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.rmi.*;
public class ClientUI extends JFrame implements ActionListener
{
private JTextField txtA,txtB,txtKQ;
private JButton btnClear,btnExit;
private JButton btnCalcAdd,btnCalcSub,btnCalcMul,btnCalcDev;
public ClientUI(){
JPanel pCen=new JPanel(new GridLayout(4,1));
JPanel p1=new JPanel();JPanel p2=new JPanel();
JPanel p3=new JPanel();JPanel p4=new JPanel();
pCen.add(p1);pCen.add(p2);pCen.add(p3);pCen.add(p4);
getContentPane().add(pCen);
//==========================================
p1.add(new JLabel(“Nhap so a”));p1.add(txtA=new JTextField(15));
p2.add(new JLabel(“Nhap so b”));p2.add(txtB=new JTextField(15));
p3.add(new JLabel(“Ket qua :”));p3.add(txtKQ=new JTextField(15));
txtKQ.setEditable(false);
p4.add(btnCalcAdd=new JButton(” + “));btnCalcAdd.addActionListener(this);
p4.add(btnCalcSub=new JButton(” – “));btnCalcSub.addActionListener(this);
p4.add(btnCalcMul=new JButton(” * “));btnCalcMul.addActionListener(this);
p4.add(btnCalcDev=new JButton(” / “));btnCalcDev.addActionListener(this);
p4.add(btnClear=new JButton(“Clear”));btnClear.addActionListener(this);
p4.add(btnExit=new JButton(“Exit”));btnExit.addActionListener(this);
setResizable(false);
setSize(350,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(300,200);
}
public void actionPerformed(ActionEvent e) {
Object o=e.getSource();
if(o.equals(btnExit)){
System.exit(1);
}
else
{
if(txtA.getText().trim().equals(“”)||txtB.getText().trim().equals(“”)){
JOptionPane.showMessageDialog(null,”Text Fields cannot be null”,
“Error”,JOptionPane.ERROR_MESSAGE);
return;
}
if(o.equals(btnCalcAdd)){
try {
CalculatorInterface obj=null;
obj=(CalculatorInterface)Naming.lookup(“//localhost/calc”);
int a=Integer.parseInt(txtA.getText());
int b=Integer.parseInt(txtB.getText());
long x=obj.Add(a,b);
txtKQ.setText(“”+x);
}catch (Exception ex) {
ex.printStackTrace();
}
}
else if(o.equals(btnCalcSub)){
try {
CalculatorInterface obj=null;
obj=(CalculatorInterface)Naming.lookup(“//localhost/calc”);
int a=Integer.parseInt(txtA.getText());
int b=Integer.parseInt(txtB.getText());
long x=obj.Sub(a,b);
txtKQ.setText(“”+x);
}catch (Exception ex) {
ex.printStackTrace();
}
}
else if(o.equals(btnCalcMul)){
try {
CalculatorInterface obj=null;
obj=(CalculatorInterface)Naming.lookup(“//localhost/calc”);
int a=Integer.parseInt(txtA.getText());
int b=Integer.parseInt(txtB.getText());
long x=obj.Mul(a,b);
txtKQ.setText(“”+x);
}catch (Exception ex) {
ex.printStackTrace();
}
}
else if(o.equals(btnCalcDev)){
try {
CalculatorInterface obj=null;
obj=(CalculatorInterface)Naming.lookup(“//localhost/calc”);
int a=Integer.parseInt(txtA.getText());
int b=Integer.parseInt(txtB.getText());
double x=obj.Div(a,b);
txtKQ.setText(“”+x);
}catch (ArithmeticException aex) {
txtKQ.setText(“Divide by zero”);
}catch (Exception ex) {
ex.printStackTrace();
}
}
else if(o.equals(btnClear)){
txtA.setText(“”);
txtB.setText(“”);
txtKQ.setText(“”);
}
}
}
public static void main(String[]args){
System.setProperty(“java.security.policy”, “client.policy”);
ClientUI cc=new ClientUI();
cc.setVisible(true);
}
}
3> Tạo File Policy tên client.policy với nội dung sau
grant {
permission java.net.SocketPermission “*:1024-65535″, “connect”;
};
4> Biên dịch với command promt (thư mục hiện hành là MyCalcClient)
javac *.java
5> Tạo file thực thi có tên MyCalclient.bat với nội dung sau
java ClientUI
//=========================================================
//=========================================================
//=========================================================
Demo ứng dụng:
1> Chạy file MyCalSVR.bat để chạy server. Nhấn nút Start để start server

2> Chạy file MyCalclient.bat để chạy client.

3> Test chương trình
Chúc thành công!
Hồng Hạnh said
Thầy ơi! Em làm theo đúng các bước hướng dẫn của Thầy mà chạy không được. Thầy xem giúp em lỗi này với nhé. Cám ơn Thầy.
************************************************************
C:\EJB\EJB_Calculator\client>javac ClientUI.java
ClientUI.java:49: cannot access CalculatorInterface
bad class file: .\CalculatorInterface.class
class file contains wrong class: Client.CalculatorInterface
Please remove or make sure it appears in the correct subdirectory of the classpa
th.
CalculatorInterface obj=null;
^
1 error
C:\EJB\EJB_Calculator\client>pause
Press any key to continue . . .
Hữu Trung said
Em chạy bằng Tool cái file ServerUI thì chạy rất tốt nhưng chạy bằng tay thì nó lại bị cái lỗi dưới đây. Thầy giải thích dùm em! Cảm ơn thầy.
————————————————————————————–
E:\Computer\Exercises\EJB\Session1\CalcServer>java ServerUI
Exception in thread “main” java.lang.NoClassDefFoundError: ServerUI
E:\Computer\Exercises\EJB\Session1\CalcServer>pause
Press any key to continue . . .
vovanhai said
Trong tùy biến môi trường path của em, thêm vào .; là ngon lành!
Pham Duy Hung said
Bài viết của thầy rất hay, em cảm ơn thầy. Em cứ nghĩ là RMI phải chạy thông qua command như là rmic, start rmiregistry, java -djava…. Hôm nay sau khi đọc được bài viết của thầy,em thấy rất hứng thú, một lần nữa em cảm ơn thầy
Cherry said
Những bài viết của thầy hay quá,
em cảm ơn thầy rất nhiều ạ!!!
tay said
thay oi em co bai nay sao no khong lay duoc dia chi ip cua cac trang web hay ten may chu trong tap tin host cua windows
package mang;
import java.net.*;
import java.io.*;
public class AddrLookupApp {
public static void main(String args[]) {
try {
if(args.length!=1){
System.out.println(“Usage: java AddrLookupApp “);
return;
}
InetAddress host = InetAddress.getByName(args[0]);
String hostName = host.getHostName();
System.out.println(“Host name: “+hostName);
System.out.println(“IP address: “+host.getHostAddress());
}catch(UnknownHostException e) {
System.out.println(“Address not found”);
return;
}
}
}
vovanhai said
Vẫn chạy bình thường. em xem lại sao ấy chứ!
Thường said
Thầy ơi! Em chạy command “javac server.java” nó báo lỗi: ‘javac’ is not recongnized as an internal or external command, operable program or batch file.
ham hoc said
thưa thầy, thầy có the giải thích hộ em new Runnable()
trong
public void actionPerformed(ActionEvent e){
Object o=e.getSource();
if(o.equals(btnStart)){
new Thread(new Runnable(){
public void run(){
try {
CalculatorInterface calc=null;
calc=new CalculatorImpl(ServerUI.this);
ctx =new InitialContext();
ctx.rebind(”rmi:calc”, calc);
lblMessage.setText(”Calculator server is running…”);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
vovanhai said
Khi new 1 interface thì ta phải implement các callback methods của interface đó. Dạng anonymous method.
Jenny said
Em dùng eclipse test bị lỗi:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: MyCalcServer.CalculatorInterface (no security manager: RMI class loader disabled)
vovanhai said
no security manager, phải them file client.policy với nội dung:
grant{
permission java.net.SocketPermission “*:1024-65535″,”connect”;
};
sau đó chạy command-line như sau:
java -Djava.Security.policy=client.policy HelloClient
hoặc đăng ký trong chương trình với cú pháp sau:
System.setProperty("java.security.policy", "client.policy");
System.setSecurityManager(new RMISecurityManager());
ham hoc said
thưa thầy thầy có thể dạy chjo em phần InitialContext();em đã tìm trên mạng nhưng ko thấy nói về phần nay nhiều;thầy có thể giải thích hộ em sao lại phải thêm ngữ cảnh nay vào trong ứng dụng,em cám ơn thầy bài viết của thầy rất hay.
vovanhai said
Bạn nên lookup từ khóa JNDI.
Duyhoat said
Thầy có thể giải thích cho e về cái Serverui đc k ạ?
Thay oi said
Làm cách nào tạo file client.policy vậy thầy ? em cũng bị lỗi tương tự như bạn ở trên
vovanhai said
dùng notepad. Nhưng nếu em demo trên máy em thôi thì vứt nó đi cũng được.
Hà Oanh said
thầy ơi! em cũng làm bài rmi như ví dụ trên của thầy.nhưng em làm giao diện kéo thả trong neatbean.em đã chạy được server và tính toán dc.nhưng khi kích vào stop thì chưa dừng được thầy àh.
private void btn_batdauActionPerformed(java.awt.event.ActionEvent evt) {
try
{
pheptinh_impl pt = new pheptinh_impl();
LocateRegistry.createRegistry(1099);
Naming.rebind(“rmi://localhost:1099/pheptinh”, pt);
txt_s.setText(“da ket noi thanh cong !”);
}
catch(Exception e)
{e.printStackTrace();}
// TODO add your handling code here:
}
đây là code để em chạy server
thầy chỉ em cách stop server với thầy! Em cảm ơn thầy !
vovanhai said
Naming.unbind(“JNDI_name”);
Hà Oanh said
Em cảm ơn thầy !(^# _ #^)
dinh cuong said
C:\Users\ANHCUONG\Documents\NetBeansProjects\Hello\src\server>java HelloServer
Exception in thread “main” java.lang.NoClassDefFoundError: HelloServer
Caused by: java.lang.ClassNotFoundException: HelloServer
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: HelloServer. Program will exi
khi em start server gap loi nay, thay giup em voi ak.. em cam on thay nhieu..
vovanhai said
biên dịch có OK không, ví dụ: java -d . *.java
Hà Thị Ngọc Trân said
thầy ơi,tạođến bước này em không hiểu cách tạo như thế nào.mở command promt ở đâu,và cách tạo file MyCalSVR.bat ở đâu? 4>Biên dịch:
Trong command promt, gõ dòng lệnh sau để biên dịch (thư mục hiện hành là MyCalcServer)
javac *.java
5> Thực thi:
Tạo file MyCalSVR.bat với nội dung sau
java ServerUI
Thầy trả lời giúp em.Cám ơn thầy rất nhiều…
Hà Thị Ngọc Trân said
thầy,em làm trong netpean ,Khi chạy server ,start xong ,em chạy client và tính.Khi nhấn tính thì hiện ra lỗi sau: Cám ơn thầy rất nhiều….
java.lang.ClassCastException: $Proxy0
at MyCalClient.ClientUI.actionPerformed(ClientUI.java:57)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3129)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
TonyTeo said
Cai cho start nay la cai gi vay thay ?
public void actionPerformed(ActionEvent e){
Object o=e.getSource();
if(o.equals(btnStart)){
new Thread(new Runnable(){
public void run(){
try {
CalculatorInterface calc=null;
calc=new CalculatorImpl(ServerUI.this);
ctx =new InitialContext();
ctx.rebind(”rmi:calc”, calc);
lblMessage.setText(”Calculator server is running…”);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}).start(); // bien dich bi bao loi cho nay hoai
Guest said
em chào thầy
em đang học về java nhưng có 1 số vấn đề mắc phải mong thầy giúp đỡ em
khi em tạo stub bằng rmic nó luôn báo
Class Not Found
mong sớm nhận phản hồi của thầy
cám ơn thầy
help said
ban nao biet cach chay mot chuong trinh nhu thay Hai bang netbean khong dup minh voii
help me said
sorry ban nao co the chi dup minh cach chay chuong trinh nay trong netbean khong.minh moi tim hieu ve rmi nen chua ro
Võ Văn Hải said
classpath của bạn không đùng thì nó báo thôi. Để ý khi compile dùng option -d.
Võ Văn Hải said
Viết code tạo 1 thread rồi cho nó start luôn thay vì phải định nghĩa 1 biến rồi cho biến đó .start
Võ Văn Hải said
Bạn thêm các dòng sau thử xem:
System.setProperty(“java.naming.factory.initial”, “org.jnp.interfaces.NamingContextFactory”);
System.setProperty(“java.naming.provider.url”,”localhost:1099″);
Võ Văn Hải said
Thư mục mà bạn tạo các file java.
minh tran said
E mới học về RMI nên còn kém chưa hiểu biết. Mong thầy và các bạn giải hộ e. Thaks tất cả mọi nguoi.
Sử dụng kỹ thuật RMI để thực hiện giải quyết các yêu cầu sau:
Client gửi đến Server 1 dãy số nguyên. Server thực hiện
a. Tính tổng dãy số đó
b. Sắp xếp dãy số đó theo thứ tự tăng dần
c. Tìm số các phần tử chẵn, lẻ trong dãy
d. Đảo ngược dãy số
e. Xóa các phần tử chia hết cho 3
Sau đó gửi trả lại cho Client
Yêu cầu viết CT thực hiện kết quả trên màn hình Client
Nguyễn Duy Quang said
Thầy !
Thầy cho em hỏi. Với bài ứng dụng như trên nhưng mà chúng ta làm với nhiều server con. tức là 1 server đảm nhiệm làm một phép tính, thì phải làm như thế nào, thầy có thể demo dùm không ạ.
thuy said
Em làm chương trình Client/Server bằng RMI đã chạy ok. Nhưng giờ em muốn lấy hostname của Client đưa lên giao diện Server khi Client truy cập gọi hàm từ Server thì làm thế nào hả Thầy? Rất mong Thầy hồi âm sớm giúp em với.
Võ Văn Hải said
thay cái tên hoặc ip của server trong code client.
Quang said
Chào Thầy ! Thầy cho em hỏi:
Em làm 1 game cho phép người chơi đánh cờ caro và chat với nhau theo TCP socket client/server giờ em chuyển game đó sang RMI, nhưng em thắc mắc là , ở client em truyền vị trí nước đi, và nhận nước đi của đối phương thông qua server rồi client kiểm tra xem khi nào thằng và thua. còn server thì chỉ việc truyền thông tin (chat + nước đi) cho 2 người chơi.
Vậy Thầy cho em hỏi, nếu em chuyển sang RMI thì phan cài đặt (em sẽ để phương thức nào trong đó) vì em thấy file server của em chỉ xử lý truyền data chứ nó hok có tính toán gì hết.
Tương tự phần chat cũng vậy, server cũng chỉ truyền data giừa 2 client.
Nhờ Thầy phân tích gợi ý cho em, phần implement caro + chat sẽ là phương thuc xu lý gì trên đó ạ
Chào Thầy !! Chúc Thầy vui khỏe
tuyen said
thank, pro
Lý Thường Kiệt said
Em chào Thầy. Em mới tìm hiểu RMI, Em viết bằng Eclipse, Em tạo ra 3 Project tương ứng là lớp dịch vụ, lớp Server và lớp Client, nhưng Em lại không biết dùng công cụ để chạy hay biên dịch. Nếu cứ bầm Ctrl F11 thì cái Project lớp dịch vụ bào là lỗi không có hamg main. Thầy có thể chỉ cho Em cách chạy và biên dịch một chương trình RMI bằng Eclipse được không ạ?
Lê Thị Phương said
Em chào thầy, em mới học RMI, em vẫn chưa biết cách chạy 1 RMI cơ bản. Em làm theo hướng dẫn của thầy thì nó không chạy được gì cả, khi nhấn file .bat nó không hiện ra cái gì hết. Em làm theo 1 số hướng dẫn khác, người ta yêu cầu phải dùng Rmic để tạo ra file _stub nhưng khi em lam vậy thì báo lỗi, mong thầy giúp đỡ:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\PHUONG>f:
F:\>cd LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG
F:\LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG>rmic Calculate
Exception in thread “main” java.lang.NoClassDefFoundError: sun/rmi/rmic/Main
Caused by: java.lang.ClassNotFoundException: sun.rmi.rmic.Main
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: sun.rmi.rmic.Main. Program will exit.
F:\LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG>
Võ Văn Hải said
Thứ nhất là từ JDK 1.5 (5) trở về sau bạn không cần phải build file stub và skeleton. Lỗi bạn gặp phải có thể là do bạn chưa thiết lập CLASSPATH, Path dúng để chạy thôi.
ellytien said
thay ah e chay thi no bao loi o server khi an nut start thi no bao loi the nay e ko hieu
java.lang.ClassCastException: mycalculatorserver.CalculatorImpl cannot be cast to mycalculatorserver.CalculatorInterface
at mycalculatorserver.ServerUI$1.run(ServerUI.java:88)
at java.lang.Thread.run(Thread.java:722)
Exception in thread “Thread-3″ java.lang.UnsupportedOperationException: Not supported yet.
at mycalculatorserver.ServerUI$1.run(ServerUI.java:97)
at java.lang.Thread.run(Thread.java:722)
Võ Văn Hải said
Em bind cái inteface hay cái Implement class? Khai báo phải là MyInterface istance =new MyImplementingClass()
Lê Thị Phương said
Xin lỗi Thầy em post nhầm, là thế này ạ:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\PHUONG>f:
F:\>cd LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG
F:\LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG>rmic Calculate
error: File .\Calculate.class does not contain type Calculate as expected, but type Goi.Calculate. Pl
ease remove the file, or make sure it appears in the correct subdirectory of the
class path.
error: Class Calculate not found.
2 errors
F:\LEARN\LAP TRINH MANG\RMI\RMI\bin\PHUONG>
khait said
cho em hỏi muốn chạy trên 2 máy thì làm thế nào ? thanks
Võ Văn Hải said
Em gửi mail bài của em tôi xem thế nào.
RMI trong java said
Em chào thầy ạ!
Em mới học về RMI và viết 1 chương trình như sau:
//Product.java: interface từ xa
import java.rmi.*;
public interface Product extends Remote{
public String getDescription() throws RemoteException;
public double getPrice() throws RemoteException;
}
//ProductImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class ProductImpl extends UnicastRemoteObject implements Product{
private String descr;
private double price;
public ProductImpl(String s,double p) throws RemoteException{
descr=s;
price=p;
}
public String getDescription() throws RemoteException{
return descr;
}
public double getPrice()throws RemoteException{
return price;
}
}
//Productserver.java
import java.rmi.*;
import java.rmi.server.*;
import sun.applet.*;
public class Productserver{
public static void main(String args[]){
try{
System.out.println(“cai dat dich vu….”);
ProductImpl p1=new ProductImpl(“lo nuong banh”,250);
Naming.rebind(“rmi://localhost/teaster”,p1);
ProductImpl p2=new ProductImpl(“lo vi song”,120);
Naming.bind(“rmi://localhost/microwave”,p2);
System.out.println(“dang ky dich vu….”);
System.out.println(“cho may khach…..”);
}catch(Exception e){
System.out.println(“Error: “+e);
}
}
}
//ProductClient.java
import java.rmi.*;
import java.rmi.server.*;
public class ProductClient{
public static void main(String args[]){
System.setSecurityManager(new RMISecurityManager());
String url=”rmi://localhost/”;
String name=”";
double price=0.0;
try{
Product c1=(Product) Naming.lookup(url+”teaster”);
Product c2=(Product)Naming.lookup(url+”microwave”);
name=c1.getDescription();
price=c1.getPrice();
System.out.println(name+”, gia ban: “+price);
price=c2.getPrice();
name=c2.getDescription();
System.out.println(name+”, gia ban: “+price);
}catch(Exception e){
System.out.println(“error: “+e);
}
System.exit(0);
}
}
sau đó em tạo 1 file client.policy với nội dung như thầy hướng dẫn.
Tất cả các file em để ở 1 thư mục, roy thực hiện các lệnh:
javac *.java
rmic ProductImpl
start rmiregistry
start java Productserver
java -Djava.security.policy=client.policy ProductClient
4 lênh đầu tiên đêif thực hiện bình thường, nhưng khi em thực hiện lênh cuối cùng thi chương trình lại thông báo lỗi : error: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect, resolve)
Em không biết tại sao và không biết sửa thế nào, mong thầy giải đáp giúp. Em cảm ơn thầy.
Lê Lâm said
Thầy ơi em bị lỗi như thế này :
C:\Program Files\Java\jdk1.6.0\bin>rmic FriendImpl
error: Class FriendImpl does not implement an interface that extends java.rmi.Remote; only remote objects need stubs and skeletons.
1 error
Em vẫn chưa khắc phục được thầy ơi,
Nguyen Tuan said
Thầy ơi Sao mấy cái Rmi này em chạy được trên cmd nhưng không thể chạy được trên Netbean.Thầy chỉ dùm em cách cấu hình để tạo một project rmi chạy trên netbean được không ạ.Em xin chân thành cảm ơn!
Võ Văn Hải said
Chạy trên Netbeans thì em chạy 2 lần trên 2 lớp là được chứ gì! (nhấn phải chuột lên lớp cần chạy, chọn Run file)
Võ Văn Hải said
nó báo rõ đấy chứ! Lớp FriendImpl của em extends UnicastRemoteObject và implements cái interface cái Remote interface của em không?
son said
Thưa thầy cho em hỏi, trong Classpath và path tạo thế nào là đúng, em chạy mà nó cứ báo lỗi
java.lang.NoClassDefFoundError: and
Caused by: java.lang.ClassNotFoundException: and
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: and. Program will exit.
Võ Văn Hải said
1. Tạo 1 biến môi trường tên JAVA_HOME với giá trị là đường dần đến thư mục cài đặt JDK của bạn( ví dụ jdk1.6.0_16).
2. Nếu đã có biến PATH rồi thì edit nó, , không thì tạo mới rồi thêm vào chuỗi sau: ;.;%JAVA_HOME%\bin
3. Nếu đã có biến CLASSPATH rồi thì edit nó, , không thì tạo mới rồi thêm vào chuỗi sau:.;
Đóng các cửa sổ lại.
Bây giờ mở cmd lên, gõ javac rồi enter, nó báo 1 mớ lung tung thứ thì OK, còn có 1 dòng chửi thì làm sai rồi.
huy_langtu said
Thầy cho em hỏi cách triển khai ứng dụng RMI viết bằng netbeans trên 2 máy khác nhau như thế nào?
Võ Văn Hải said
Triển khai ứng dụng RMI viết bằng netbeans trên 2 máy khác nhau như thế nào
Build server, build client
Code Server chạy trên server
Copy file jar client về phía client mà chạy.
Chú ý cái địa chỉ máy chủ.
minh thanh said
thầy ơi!cũng với yêu cầu này nhưng làm bằng socket thì thế nào ah?phần giao diện cũng khó mà phần đưa ra cổng LPT em cũng đang gặp rắc rối ah!!!!!!!!cám ơn thầy nhiều!
Thanh Tình said
chương trình lại thông báo lỗi : error: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect, resolve)
Nguyen Duc Tho said
thua thay sao em chay toan thay bao loi unclosed character literal voi ‘;’ expected vay ak?
gia linh said
thày cho e hỏi: sau làm các bước như trên, e vào chạy file server thì nó báo lỗi thế này thì sửa làm sao ạ ?
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: OpenFileInterface
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:413)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Unknown Source)
at OpenFileServer.main(OpenFileServer.java:12)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: OpenFileInterface
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:403)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: OpenFileInterface
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:730)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:674)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:611)
at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:646)
at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:311)
at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:257)
at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1549)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1511)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
… 13 more
Võ Văn Hải said
“chương trình lại thông báo lỗi : error: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:1099 connect, resolve)”
Bạn thử tạo 1 file có tên client.policy với nội dung
grant { permission java.net.SocketPermission "*:1024-65535", "connect"; };sau đó trong code client thêm dòng sau:
Trong quá trình chạy file, em dùng command-line ở dạng
hoàng phúc said
em thấy những bài viết của thầy rất hay và giúp cho em rất nhiều.thầy ơi muốn học tốt java ta cần bất đầu từ đâu thưa thầy
Nguyễn Thanh Tình said
cho em hỏi: mình tạo classpath cụ thể như thế nào à?
trong variable đầu tiên e đã thiết lập như sau:
JAVA_HOME: C:\Program Files\Java\jdk1.5.0_01\bin
PHATH: C:\Program Files\Java\jdk1.5.0_01\bin
Phần Variable của ô dưới thì thiết lập classpath như thế nào ạ? Thầy giúp giùm em
em đang cài JDK1.5.0 trên windown xp2 và đàn xài NetBeans IDE5.0
e đã tạo ra các file:
Võ Văn Hải said
JAVA_HOME= C:\Program Files\Java\jdk1.5.0_01
PATH = %JAVA_HOME%\bin
Nguyễn Thanh Tình said
//Imlement.java
import java.rmi. server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class Imlement extends UnicastRemoteObject implements Interface {
public Imlement() throws RemoteException {
super();
}
public String getDLtuCSDL(String tukhoa) {
// day là doan code ket noi CSDL de lay DL
return “Xin chao:” + tukhoa;
}
}
//Interface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Interface extends Remote {
String getDLtuCSDL(String tukhoa) throws RemoteException;
}
//Server.java
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
public class Server {
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
System.out.println(“HelloObject is registried1″);
Imlement obj = new Imlement();
System.out.println(“HelloObject is registried.”);
Naming.rebind(“DLServer”, obj);
System.out.println(“HelloObject is registried”);
} catch (Exception e) {
System.out.println(“Error: ” + e);
}
}
}
//Tạo file policy.txt
grant {
permission java.security.AllPermission;
};
//ThuVienApplet.java (Đây là JavaApplet nhúng vào html)
import java.rmi.Naming;
import javax.swing.JOptionPane;
/*
* ThuVienApplet.java
*
* Created on November 25, 2011, 9:22 PM
*/
/**
*
* @author tinh
*/
public class ThuVienApplet extends java.applet.Applet {
/** Initializes the applet ThuVienApplet */
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// //GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txttukhoa = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jLabel3 = new javax.swing.JLabel();
setLayout(new java.awt.BorderLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(1000, 56));
jLabel1.setFont(new java.awt.Font(“Microsoft Sans Serif”, 1, 36));
jLabel1.setText(“TRA C\u1ee8U C\u01a0 S\u1ede D\u1eee LI\u1ec6U S\u00c1CH”);
jLabel1.setPreferredSize(new java.awt.Dimension(600, 50));
jPanel1.add(jLabel1);
jLabel2.setFont(new java.awt.Font(“Microsoft Sans Serif”, 1, 14));
jLabel2.setText(“Nh\u1eadp t\u1eeb kh\u00f3a c\u1ea7n t\u00ecm:”);
jLabel2.setPreferredSize(new java.awt.Dimension(170, 20));
jPanel1.add(jLabel2);
txttukhoa.setColumns(20);
txttukhoa.setRows(1);
jPanel1.add(txttukhoa);
txttukhoa.getAccessibleContext().setAccessibleParent(jScrollPane2);
jButton1.setFont(new java.awt.Font(“Microsoft Sans Serif”, 1, 14));
jButton1.setText(“T\u00ecm ki\u1ebfm”);
jButton1.setAutoscrolls(true);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jPanel1.add(jScrollPane2);
jScrollPane2.getAccessibleContext().setAccessibleParent(jScrollPane2);
jLabel3.setText(“jLabel3″);
jLabel3.setPreferredSize(new java.awt.Dimension(400, 300));
jPanel1.add(jLabel3);
add(jPanel1, java.awt.BorderLayout.CENTER);
}// //GEN-END:initComponents
//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String helloURL = “rmi://192.168.1.101/Doituongketnoi”;
Interface object = null;
try {
object = (Interface)Naming.lookup(helloURL);
String message = object.getDLtuCSDL(txttukhoa.getText());
JOptionPane.showConfirmDialog(null,message);
jLabel3.setText(message);
} catch (Exception e) {
JOptionPane.showConfirmDialog(null,”Client Error :” + e);
}
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration – do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea txttukhoa;
// End of variables declaration//GEN-END:variables
}
Cài đặt biến môi trường:
C:\Program Files\Java\jdk1.5.0_01\bin
PHATH: C:\Program Files\Java\jdk1.5.0_01\bin
JAVA_HOME= C:\Program Files\Java\jdk1.5.0_01
PATH = %JAVA_HOME%\bin
Các bước em biên dịch:
Khởi động dịch vụ RMIREGISTRY
start rmiregistry -J-classpath -J.
chạy tốt
Biên dịch các file javac *.java trong thư mục đều chạy tốt
rmic Imlement tạo được Stub
Sau đó chạy lệnh policy với cấu trúc
D:\Demo_detaithuctap\Server>java -Djava.security.policy=file:///d:/Demo_detaith
ctap/Server/policy.java Server
HelloObject is registried1
HelloObject is registried.
Error: java.security.AccessControlException: access denied (java.net.SocketPerm
ssion 127.0.0.1:1099 connect,resolve)
Lỗi này chỉ xuất hiện trên máy e, còn trước đây em làm một máy tính khác thì không lỗi, nhưng copy qua cái laptop chỉnh hoài ko dc.
Thư mục mà em chứa: D:\Demo_detaithuctap\Server
Thầy giúp em xem lỗi nó thế nào? Em mò hoài mà chả được nản quá thầy ơi!
E tốt nghiệp năm 2005 giờ thấy java thích học mới học nên còn nhiều điều chưa biết mong thầy chỉ giúp?
Cảm ơn thầy nhiều!
Mong nhận được câu trả lời sớm từ thầy!
Hung said
Thay oi ! thầy có thể nói rõ cho em phần RMI callback được không ạ ? và cho em một ít tài liệu về phần này ! Em chân thành cảm ơn !
Võ Văn Hải said
“Biên dịch các file javac *.java trong thư mục đều chạy tốt
rmic Imlement tạo được Stub
Sau đó chạy lệnh policy với cấu trúc
D:\Demo_detaithuctap\Server>java -Djava.security.policy=file:///d:/Demo_detaith
ctap/Server/policy.java Server
HelloObject is registried1
HelloObject is registried.
Error: java.security.AccessControlException: access denied (java.net.SocketPerm
ssion 127.0.0.1:1099 connect,resolve)”
Có 1 chỗ tôi thấy chưa đúng trong cmd của bạn:
D:\Demo_detaithuctap\Server>java -Djava.security.policy=file:///d:/Demo_detaith
ctap/Server/policy.java Server
file policy của bạn sao lại là policy.java? bạn nên tạo 1 file dạng text có phần mở rộng là policy(chẳng hạn client.policy) rồi gõ nội dung sau:
grant{ permission java.net.SocketPermission "*:1024-65535","connect"; };sau đó chạy client theo kiểu: java -Djava.security.policy=client.policy TenLopClient nhé!
Thanh Tình said
Thầy ơi cho em hỏi em muốn kết nối csdl trên sql server 2000 với java thì em làm thế nào à?
Một số tài liệu hướng dẫn kết nối thông qua JDBC.
Vậy cách thực hiện nó như thế nào?
Bonty said
thay cho e hoi e ket noi coi csdl ma sao bi loi nay ha thay
server.ServerView btStartActionPerformed
SEVERE: null
java.lang.Exception: Error: Khong The Ket Noi Den Database Server …jdbc:sqlserver://127.0.0.1:1433;databaseName=QLTRUONGHOC;user=sa;password=saThe server version is not supported. The target server must be SQL Server 2000 or later.
at server.SQLConnection.excuteQuery(SQLConnection.java:91)
at server.ServerView.btStartActionPerformed(ServerView.java:574)
at server.ServerView.access$800(ServerView.java:34)
at server.ServerView$4.actionPerformed(ServerView.java:185)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Mong thầy hướng dẫn viết chương trình NotePad theo RMI said
Thầy ơi, thầy cho em hỏi là em đang cần viết chương trình NotePad theo RMI ? Rất mong thầy hướng dẫn cho em, thật tình em mới học java nên cũng chưa rành. em không biết bây giờ em cần xây dựng các class nào ở sever và class nào ở client. Mong sớm nhận được hồi âm của thầy.