我才刚刚开始学习Java。我的任务是创建一个文件服务器,它使用线程从多个客户端接受某些命令,例如 File Get、File Put 和 File Delete。我正在使用自定义类 DataObject 来序列化和发送命令以及可能伴随的任何数据。客户端是交互式的,因为它涉及到各种命令的手动用户输入。这意味着由于 EOFException,ObjectInputStream readObject() 函数将无法在 while(true) 循环中工作。我该怎么做才能使服务器线程在 readObject() 处暂停,直到它看到下一个对象然后恢复 while(true) 循环?
服务器上的代码(分别为每个线程运行):
public void run() {
ObjectInputStream is = null;
ObjectOutputStream os = null;
try{
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
input = (DataObject) is.readObject();
//System.out.println("Input has been read");
output = CommandProcessor.process(input);
if(output.data == null) {
os.writeObject(output);
if(output.message.compareToIgnoreCase("Rsp Bye")==0){
clientSocket.close();
}
}
}
}
客户端代码:
public Talker() {
DataObject input = new DataObject(0), output = new DataObject(0);
try {
log = new PrintStream("/home/meher/log.txt");
InetAddress serverAddress = InetAddress.getByName("127.0.0.1");
Socket serverSocket = new Socket(serverAddress, port);
os = new ObjectOutputStream(serverSocket.getOutputStream());
is = new ObjectInputStream(serverSocket.getInputStream());
CommandExecuter.Hello(output);
write(output);
read(input);
while(not-end-of-user-input){ //Yet to code this part
//Execute commands
}
}