gpt4 book ai didi

java - 数据输入流

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

我在服务器端有这个代码:

服务器端:

 ServerSocket listenTransferSocket = new ServerSocket(6000);
Socket connectionTransferSocket = listenTransferSocket.accept();

DataOutputStream outTransferToClient =
new DataOutputStream(connectionTransferSocket.getOutputStream());
{
....................... (Some code)
.......................
}
outTransferToClient.write(fileInBytes,0,numOfBytes);
System.out.println("File send");
**// outTransferToClient.close();**

BufferedReader inFromClientR =
new BufferedReader(new InputStreamReader(connectionTransferSocket.getInputStream()));

客户端:

Socket fileTransferSocket = new Socket("localhost",6000);
DataInputStream in = new DataInputStream(new BufferedInputStream(
fileTransferSocket.getInputStream()));

OutputStream out = new FileOutputStream(new File("./TransferedFiles/"+fileName));

byte[] by = new byte[numOfBytes];

while ((read = in.read(by, 0, numOfBytes)) != -1) {

out.write(by,0,read);
}

DataOutputStream outToServerR =
new DataOutputStream(fileTransferSocket.getOutputStream());
System.out.println("checkC");
outToServerR.writeBytes("Transfer completed \n");

如果我关闭它,当我尝试打开 BufferedReader 时,我会收到以下异常:outTransferToClient.close();

Exception in thread "main" java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:788)
at Server.main(Server.java:92)

如果我不让客户端的 while 循环永远不会停止..有什么帮助吗???

最佳答案

DataOutputStream 扩展了 FilterOutputStream,它具有 close() 方法

来自docs

Closes this output stream and releases any system resources associated with the stream.
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

另外,在finally block 中使用像close()这样的方法总是一个很好的做法

关于java - 数据输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15805971/

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