首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataInputStream

DataInputStream
EN

Stack Overflow用户
提问于 2013-04-04 16:20:41
回答 2查看 1.1K关注 0票数 0

我在服务器端有以下代码:

服务器端:

代码语言:javascript
复制
 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()));

客户端:

代码语言:javascript
复制
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();

代码语言:javascript
复制
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循环永远不会停止..有什么帮助吗?

EN

回答 2

Stack Overflow用户

发布于 2013-04-04 16:23:48

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

来自docs

代码语言:javascript
复制
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块中使用close()这样的方法总是一种很好的做法

票数 1
EN

Stack Overflow用户

发布于 2013-04-04 16:25:54

是的,关闭一个DataOutputStream也会关闭底层的OutputStreamDataOutputStream#close()的Javadoc声明:

FilterOutputStream的close方法调用其flush方法,然后调用其基础输出流的close方法。

另外,Javadoc for Socket声明当您关闭SocketinputStreamoutputStream时,它也会关闭相关的套接字。

因此,在关闭包装了套接字的两个流的DataOutputStream之后,不能重用该套接字。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15805971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档