2013-04-04 80 views
0

我有服务器端验证码:DataInputStream类

服务器端:

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

+0

注意:如果您使用的是Java SE 7,请考虑使用新的自动资源管理功能关闭您的流。 – Puce 2013-04-04 08:40:14

+0

可能重复的[DataInputStream永不停止](http://stackoverflow.com/questions/15807999/datainputstream-never-stops) – 2013-04-04 15:45:22

回答

1

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块

0

是,关闭DataOutputStream也关闭了底层的OutputStream。 Javadoc为DataOutputStream#close()指出:

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

加上,Javadoc for Socket指出,当您关闭Socket小号inputStreamoutputStream,它也将关闭关联套接字。

因此,在关闭包装其任一流的DataOutputStream之后,您无法重新使用该套接字。

+0

首先谢谢你们两个.. 事情是,如果我不关闭这个DataOutputStream然后当我收到(使用inFromClientR.readine())程序循环永远..(和在客户端一切都很好,我不会忘记'\ n') – Nicolaos 2013-04-04 08:31:09

+0

也许你应该添加这段代码到你的问题(或开始新问题,不确定哪一个最好)。现在,很难回答,因为我们看不到你的代码的作用。 – mthmulders 2013-04-04 08:39:31

+0

会尽力感谢..... – Nicolaos 2013-04-04 08:46:01