java - 不使用 Java 套接字中的 ObjectInputStream 读取任何内容
问题描述
我创建了一个简单的服务器和一个客户端,但服务器无法读取从客户端发送的任何内容。发送字符串后,我还添加了一条打印语句,但也无法打印。
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 并使用缓冲区读取字节,我尝试了其他方法,如下所示: 服务器代码
这是客户端代码:客户端代码
上面两个链接中的代码可以工作。但是,如果我尝试使用 ObjectInputStream,它将无法正常工作:
这是服务器:服务器
这是客户:客户
这是我要发送的消息对象:消息类
有人可以为我解释一下吗?谢谢!
解决方案
要从套接字读取字符串,请使用以下内容:
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
String message = input.readUTF();
您可以从一个套接字打开多个流,因此如果您想读取真正需要 ObjectInputStream 的其他内容,也可以打开它。不要忘记正确关闭流和套接字。
推荐阅读
- netbeans - Windows 7 BSOD 后无法从 netbeans 启动 weblogic
- jprofiler - jprofiler。如何在linux上导出结果
- json - SoapUI REST + JSON 模拟服务:如何在响应中从请求中返回数据?
- angular - SVG 不会在 pdf 文件中呈现(使用 pdfmake 和 html2canvas)
- string - SAS - 在字符串上放置空格
- c# - MVC 处理任何请求的 401 响应
- c# - 从引用为 .dll 文件的库中加载图像
- javascript - 我只使用 JavaScript 创建了一个包含一些记录的表,我想将我的数组与对象设置为本地存储
- kubernetes - istio 的细粒度授权解决方案
- python - 如何在没有聚合函数的情况下使用 pandas 滚动函数?