Java 为什么我的服务器响应打印不正确?
我正在为考试而学习,正在做下面的示例题。我有一个简单的服务器,我正试图连接到一个客户端。连接似乎工作正常,但出于某种原因,这是我在客户端控制台中得到的输出。谁能告诉我为什么会这样 注意:如果有人可以建议怎么做,我也可以从客户端访问Message类(我没有这样做,因为我不确定这会有什么帮助,但我认为这是解决这个问题的关键) 此外,我所做的任何更改都必须是客户端的代码。服务器端代码无法更改。我也在下面附上了我的代码。谢谢Java 为什么我的服务器响应打印不正确?,java,Java,我正在为考试而学习,正在做下面的示例题。我有一个简单的服务器,我正试图连接到一个客户端。连接似乎工作正常,但出于某种原因,这是我在客户端控制台中得到的输出。谁能告诉我为什么会这样 注意:如果有人可以建议怎么做,我也可以从客户端访问Message类(我没有这样做,因为我不确定这会有什么帮助,但我认为这是解决这个问题的关键) 此外,我所做的任何更改都必须是客户端的代码。服务器端代码无法更改。我也在下面附上了我的代码。谢谢 public class Client { public static voi
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 8999); // create a new socket
InputStream instream = s.getInputStream(); // Create input Stream obkect
OutputStream outstream = s.getOutputStream(); // Create output stream
// object
Scanner in = new Scanner(instream); // Create scanner object that takes
// the instream as an argument
PrintWriter out = new PrintWriter(outstream); // Create a printwriter
// outstream object
String request="GET / HTTP/1.0\n\n";
out.print(request); // pass the request to the outstream
out.flush(); // moves all the data to the destination
String response = in.nextLine(); // response is the next line in the
// input stream
System.out.println("Receiving: " + response); // Print statement
s.close(); // close the socket
}
}
public class TimeServer {
private static Date currentDateAndTime() {
return new Date();
// (An object of class Date comprises time and date)
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8999);
while (true) {
Socket socket = serverSocket.accept();
try {
ObjectOutputStream stream = new ObjectOutputStream(
socket.getOutputStream());
Date dt = currentDateAndTime();
Message m = new Message(dt);
stream.writeObject(m);
stream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
class Message implements Serializable {
//This helper class can be used both by server and client code
Date timeAndDate;
// (Objects of class Date comprise time & date)
Message(Date timeAndDate) {
this.timeAndDate = timeAndDate;
}
}
您只需要修改客户端:
Scanner in = new Scanner(instream); // Create scanner object that takes
// the instream as an argument
取代
ObjectInputStream in = new ObjectInputStream(instream);
同时修复输入流的读取,替换:
String response = in.nextLine();
System.out.println("Receiving: " + response);
与:
这似乎是IDEEclipse的一个问题。。请更改eclipse的工作区并重试。当您说要更改工作区时,您的意思是离开工作区,然后返回到同一工作区并再次运行吗?如果是这样的话,它没有任何效果。我有许多其他项目在这个工作区中运行,没有任何问题,但不知道这是否意味着什么。谢谢,我的意思是说,将您的工作区更改为文件系统中的某个其他目录(不是同一个目录)。请共享您的服务器代码。似乎您的写入对象(如日期)无法输出。最好是写文字…谢谢你的帮助!成功了。我理解我的错误。我把对象当作字符串处理。谢谢
Message response = (Message) in.readObject();
System.out.println("Receiving: " + response.timeAndDate);