【问题标题】:DataInputStream数据输入流
【发布时间】:2013-04-04 08:20:40
【问题描述】:

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

服务器端:

 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 循环永远不会停止.. 任何帮助????

【问题讨论】:

  • 注意:如果您使用的是 Java SE 7,请考虑使用新的自动资源管理功能来关闭您的流。

标签: java sockets datainputstream dataoutputstream


【解决方案1】:

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

来自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 块中使用 close() 之类的方法总是一个很好的做法

【讨论】:

    【解决方案2】:

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

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

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

    因此,在关闭了封装其任一流的DataOutputStream 后,您将无法重用该套接字。

    【讨论】:

    • 首先谢谢你们俩..问题是,如果我不关闭此 DataOutputStream,那么当我收到(使用 inFromClientR.readine())时,程序将永远循环..(并且在客户端一切很好。我不会忘记'\n')
    • 也许您应该将那段代码添加到您的问题中(或开始一个新问题,不确定哪个最好)。现在很难回答,因为我们看不到你的代码做了什么。
    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    相关资源
    最近更新 更多