gpt4 book ai didi

java - 读取我从 Java 服务器发送的对象

转载 作者:行者123 更新时间:2023-12-01 14:42:27 25 4
gpt4 key购买 nike

您好,我正在尝试将一个对象发送到服务器,然后在服务器接收到该对象后,从服务器获取同一对象并将其作为客户端输出中的字符串读取。我最初发送的消息似乎有效,而之后的所有消息都无效,这是我的代码:

import java.io.*;
import java.net.*;


public class GUGLi {
static Socket socket = null;
static ObjectOutputStream out = null;
static ObjectInputStream in = null;
String host = "host";

public static void main(String[] args) throws IOException {

try {
OpenPort();
InfoSent();
ReadInfo();



String line;
while ((line = in.toString()) != null) {
System.out.println(line);
}

} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + "host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + "host");
System.exit(1);
in.close();
socket.close();
out.close();
}
}
public static void OpenPort() throws UnknownHostException, IOException{
socket = new Socket ("host", 7879);
}
public static void InfoSent()throws IOException {
Student info = new Student (22, "Guglielmo", "Male",
"email", "#");
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(info);
System.out.println("Sent: " + info);
out.flush();
}
public static void ReadInfo()throws IOException {
in = new ObjectInputStream(socket.getInputStream());


}
}

最佳答案

line = in.toString() 不读取行。它将 InputStream 转换为其字符串表示形式。您需要调用读取方法。如果您希望读取行,则需要 BufferedInputStream.readLine()。但是,如果您通过同一套接字读取对象,则无法混合流/读取器类型,因此您应该使用 readUTF() 读取并使用 writeUTF() 写入另一端。

关于java - 读取我从 Java 服务器发送的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15816916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com