我写了一个小的rmi客户端服务器程序,将Celsius转换为Fahrenheit。 当我创建一个控制台客户端连接到服务器时,它工作正常。但是当我创建一个扩展JApplet类的基于GUI的客户端时,客户端运行不正常。每当我运行客户端时,它都会抛出一条消息“ 错误:访问被拒绝(”java.net.SocketPermission“”127.0.0.1:1099“”connect,resolve“) 。如何解决这个问题?
import java.rmi.*;
public interface ConvServerInterface extends Remote{
public double celToFah(double cel)throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class ConvServerMainClass extends UnicastRemoteObject implements ConvServerInterface {
public ConvServerMainClass() throws Exception{}
@Override
public double celToFah(double cel) throws RemoteException {
return ((cel*(9.0/5.0)+32));
}
public static void main(String[] args) throws Exception
{
ConvServerMainClass serverObj = new ConvServerMainClass();
Naming.rebind("Conversion",serverObj);
System.out.println("Server is ready to receiver request!");
}
}
import java.rmi.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ConvClient extends JApplet implements ActionListener{
JLabel lblCel, lblFah;
JTextField txtCel, txtFah;
JButton btnConv;
JPanel pnl;
public void init()
{
initComp();
setActionListner();
addComponents();
}
public void initComp()
{
lblCel = new JLabel("Celsius: ");
lblFah = new JLabel("Fahrenheit: ");
txtCel = new JTextField(13);
txtFah = new JTextField(13);
btnConv = new JButton("Convert");
pnl = new JPanel();
}
public void setActionListner()
{
btnConv.addActionListener(this);
}
public void addComponents()
{
pnl.setLayout(new GridLayout(3,2));
pnl.add(lblCel); pnl.add(txtCel);
pnl.add(lblFah); pnl.add(txtFah);
pnl.add(btnConv);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(pnl);
}
@Override
public void actionPerformed(ActionEvent e) {
double cel, fah;
try{
if(System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
}
ConvServerInterface serobj = (ConvServerInterface) Naming.lookup("rmi://localhost/Conversion");
if(e.getSource()==btnConv)
{
cel = Double.parseDouble(txtCel.getText());
fah = serobj.celToFah(cel);
txtFah.setText(String.valueOf(fah));
}
}
catch(Exception ex){
txtFah.setText("Error: "+ ex.getMessage());
}
}
}
首先,我编译了服务器端接口和类文件。然后,我通过
创建了一个Stub Class _rmic ConvServerMainClass_
然后,我通过
启动我的注册表 _rmiregistry_
然后,我按
运行我的服务器类文件 _rmiregistry_
最后,我将Server Interface Class文件和Stub Class文件复制到客户端,然后我编译并运行我的客户端
_javac ConvClient.java_
_appletviewer ConvClient.java_