我正在攻读考试,正在研究以下示例问题。我有一个简单的服务器,我试图与客户端连接。连接工作正常,但由于某种原因,这是我在客户端控制台中获得的输出。谁能告诉我为什么会这样?
注意:我也可以从客户端访问Message类(我没有这样做,因为我不知道这有什么用,但我认为这是解决这个问题的关键)如果有人可以提出如何做的建议。
此外,我所做的任何更改都必须是客户端的代码。服务器端代码无法更改。我也在下面附上了我的代码。感谢
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;
}
}
答案 0 :(得分:1)
您只需要修改客户端:
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);
使用:
Message response = (Message) in.readObject();
System.out.println("Receiving: " + response.timeAndDate);