我正在尝试启动一个RMI程序,该程序允许服务器向客户端发送3个问题,客户端将接收答案并将其发送回服务器。到目前为止,在服务器上我发送问题并得到答案,但服务器自动调用getAnswer()方法,该方法不存储用户输入的内容。
这是我运行服务器和客户端时获得的控制台结果:
Server Started
0
0
Client connected, sending acknowledgement
received answer from client: 3
正如您所看到的,它在客户端连接之前调用了getAnswer()方法,因此尽管没有给出答案,但为什么显示了2个值。 如何让服务器只在我需要时调用这些方法?我已经尝试过循环和if语句,但我认为没有任何作用!
服务器代码:
import java.rmi.*;
public class Server
{
public static void main(String a[]) throws Exception
{
int answer1, answer2, answer3;
System.out.println("Server Started");
try
{
Implement obj = new Implement();
Naming.rebind("remote", obj);//register name with registry
obj.sendQuestion(question1);
answer1 = obj.getAnswer();
obj.sendQuestion(question2);
answer2 = obj.getAnswer();
} catch(Exception e)
{
e.printStackTrace();
}
}
static String question1 = "Q1: (A+B)*(A+B)\n1. A*A+B*B\n2. A*A+A*B+B*B\n3. A*A+2*A*B+B*B";
static String question2 = "Q2: (A+B)*(A-B)\n1. A*A+2*B*B\n2. A*A-B*B\n3. A*A-2*A*B+B*B";
static String question3 = "";
}
客户代码:
import java.rmi.*;
import java.util.Scanner;
public class Client
{
public static void main(String a[]) throws Exception
{
try {
Interface obj = (Interface)Naming.lookup("remote"); //looks for object with add in name
Interface m = (Interface) obj;
System.out.println(obj.sendMessage()); //retrieve message from server
System.out.println(obj.receiveQuestion());
System.out.println("Please enter your answer");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
obj.test(input);
System.out.println(obj.receiveQuestion());
} catch(Exception e)
{
e.printStackTrace();
}
}
}
接口代码:
import java.rmi.Remote;
public interface Interface extends Remote //becomes a remote interface
{
public String sendMessage() throws Exception;
public void test(int message) throws Exception;
public void sendQuestion(String message) throws Exception;
public String receiveQuestion() throws Exception;
public int getAnswer() throws Exception;
}
实施代码:
import java.rmi.server.*;
public class Implement extends UnicastRemoteObject implements Interface
{
String msg;
int answer;
public Implement() throws Exception //constructor to handle exceptions
{
super();
}
public String sendMessage()
{
String msg = "You have connected to the server";
System.out.println("Client connected, sending acknowledgement");
return msg;
}
public void sendQuestion(String message)
{
msg = message;
}
public String receiveQuestion()
{
return msg;
}
public void test(int message)
{
answer = message;
System.out.println("received answer from client: " +answer);
}
public int getAnswer()
{
System.out.println(answer);
return answer;
}
}
答案 0 :(得分:1)
你有这个回到前面。您在服务器中调用自己的远程方法。应该调用远程方法的是客户端。根据您的描述,您希望服务器成为客户端,客户端成为服务器。