2012-12-17 91 views
-1

最近我又開始使用Java了,但是我很擔心RMI。我設法使用無效函數來工作,但似乎無法通過網絡返回字符串。用Java RMI返回一個字符串

有誰知道我在做什麼錯?

Main.java:

package RMI; 

import java.rmi.RemoteException; 
import java.rmi.server.UnicastRemoteObject; 
import java.util.Random; 

public class Main extends UnicastRemoteObject implements Main_Interface { 
    private Random random; 
    private boolean coin = false; 

    public Main() throws RemoteException { ; } 

    public String flipCoin() throws RemoteException { 
     coin = random.nextBoolean(); 

     if(coin) { 
      System.out.println("Throwing Head"); 
      return "Head"; 
     } else { 
      System.out.println("Throwing Tail"); 
      return "Tail"; 
     } 
    } 

    public void test() throws RemoteException { 
     System.out.println("Test succesful"); 
    } 
} 

Main_Interface.java:

package RMI; 

import java.rmi.Remote; 
import java.rmi.RemoteException; 

public interface Main_Interface extends Remote { 
    String flipCoin() throws RemoteException; 
    void test() throws RemoteException; 
} 

Client.java(從不重要代碼剝離):

package Client; 

import RMI.Main_Interface; 
import java.io.*; 
import java.net.InetAddress; 
import java.rmi.Naming; 
import java.rmi.registry.LocateRegistry; 
import java.rmi.registry.Registry; 

public class Client { 
    public static void main(String[] args) { 
     String   line = null; 
     boolean   coin = false; 
     Main_Interface conn = null; 

     try { 
      String location = InetAddress.getLocalHost().getHostName(); 
      Registry myRegistry = LocateRegistry.getRegistry(location, 1099); 
      conn = (Main_Interface) myRegistry.lookup("ISA"); 
      //conn = (Main_Interface) Naming.lookup("ISA"); 
     } catch (Exception e) { 
      System.out.println("Server could not be found at "+location); 
      System.exit(0); 
     } 

     try { 
      conn.test() 
      System.out.println("Here"); 
      if(conn.flipCoin().equals("Head")){ 
       System.out.println("Succes"); 
      } 
      System.out.println("Here"); 
      if(coin) { 
       System.out.println("Throwed Head"); 
      } else { 
       System.out.println("Throwed Tail"); 
      } 
     } catch (Exception e) { 
      System.out.println("Could not execute the command..."); 
     } 
    } 
} 

正如你可以probally猜測, test()函數將完美執行,但flipCoin()函數將拋出該exeption。

+0

拋出什麼異常? – EJP

回答

3

究竟拋出了什麼樣的異常?

如果這是一個NullPointerException:你永遠不會在你的Main類中初始化random。把random = new Random();放在你的構造函數中

+0

感謝您的回答!它拋出一個NullPointerException異常,如果我改變函數簡單地'返回「測試」;'它的工作。愚蠢的錯誤... – Sietse