gpt4 book ai didi

java - 不使用 Java 套接字中的 ObjectInputStream 读取任何内容

转载 作者:行者123 更新时间:2023-12-01 18:03:31 24 4
gpt4 key购买 nike

我创建了一个简单的服务器和一个客户端,但服务器无法读取从客户端发送的任何内容。我在发送字符串后还添加了一条打印语句,但也无法打印。

public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(6666);

Socket clientSocket = serverSocket.accept();
System.out.println("accepting client at address " + clientSocket.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());

String input = (String) in.readObject();
System.out.println(input);
out.writeObject("Received");
out.flush();
}
}

下面是客户端,我只想发送一个字符串“??????不发送”:

 public class Test {

public static void main(String[] args) throws IOException, ClassNotFoundException {
Client client = new Client();
client.sentInfo();
}

private static class Client {

private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;

public Client() throws IOException {
Socket socket = new Socket("127.0.0.1", 6666);
this.objectInputStream = new ObjectInputStream(socket.getInputStream());
this.objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
}

public void sentInfo() throws IOException, ClassNotFoundException {
this.objectOutputStream.writeObject("?????does not send");
this.objectOutputStream.flush();
System.out.println("????????");
Message resp = (Message) this.objectInputStream.readObject();
System.out.println(resp.getMessage());
}

}
}
<小时/>

我尝试了其他方法,如果我只使用 InputStream 并使用缓冲区来读取字节,如下所示: Server code

这是客户端代码:client code

上面两个链接中的代码可以工作。但是,如果我尝试使用 ObjectInputStream,它将不起作用:

这是服务器:server

这是客户端:client

这是我要发送的消息对象:Message class

有人可以帮我解释一下吗?谢谢!

最佳答案

要从套接字读取字符串,请使用如下内容:

DataInputStream input = new DataInputStream(clientSocket.getInputStream());
字符串消息 = input.readUTF();

您可以从套接字打开多个流,因此如果您想读取真正需要 ObjectInputStream 的其他内容,也可以打开它。不要忘记正确关闭流和套接字。

关于java - 不使用 Java 套接字中的 ObjectInputStream 读取任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60594734/

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