你好堆栈溢出世界,我一直在努力解决Java IO中最直接和最常见的问题,有一段时间了,现在需要你的帮助来解决它。
在thread.run()中查看我在try块中的这段代码:
// connect to client socket, and setup own server socket
clientSocket = new Socket(serverHostname, CLIENT_PORT);
//send a test command to download a file
String downloadFileName = "sample.txt";
DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Sending a request to download file : " + downloadFileName + " from user: Arsa node"); //todo: replace with node user later
dataOutputStream.writeUTF("D/sample.txt");
//close socket if host isn't detected anymore, and if socket doesn't become null suddenly
dataOutputStream.flush();
dataOutputStream.close();
System.out.println("****File has been sent****");
in = new DataInputStream(clientSocket.getInputStream());
byte[] retrievedFileData = new byte[8036];
if (in.readInt() > 0) {
System.out.println("Starting file download!");
in.read(retrievedFileData);
System.out.println("File data has been read, converting to file now");
//closing input stream will close socket also
in.close();
}
clientSocket.close();
2令我困惑的主要问题:
总的来说,将一些东西写入套接字,然后读取并摄取它的响应应该不复杂......这似乎不是这里的情况,任何帮助将不胜感激!如果需要ServerSocket代码片段,我很乐意分享。
观察到的行为只是close()
的副作用,因为它在关闭之前调用flush()
以确保发送任何缓冲数据。要解决您的问题,您需要调用flush()
方法而不是关闭。
这种行为并非DataOutputStream
所独有:许多其他OutputStream
(或Writer
)实现都应用缓冲,当您想要确保将数据发送到客户端,写入磁盘或以其他方式处理时,您将需要刷新。
BETWEEN:DataOutputStream
和DataInputStream
用于特定于Java的非常特定类型的数据序列化协议。您可能需要仔细考虑这是否是正确的协议。