【发布时间】:2015-03-03 21:33:07
【问题描述】:
我正在尝试启动一个 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;
}
}
【问题讨论】:
-
在客户端控制台上,尽管我尝试先从服务器发送 question1,但两次都发送 question2
标签: java client-server rmi