2012-06-12 194 views
0

我的客戶端可以正常發送圖像到服務器,但是當涉及到文本文件時,它們會到達空的位置。任何想法我做錯了什麼?我非常感謝幫助,因爲我一直在努力使這項工作多少天。謝謝。能夠通過套接字發送圖像,但不能發送文本文件

這裏是服務器代碼:

class TheServer { 

    public void setUp() throws IOException { // this method is called from Main class. 
     ServerSocket serverSocket = new ServerSocket(1991); 
     System.out.println("Server setup and listening..."); 
     Socket connection = serverSocket.accept(); 
     System.out.println("Client connect"); 
     System.out.println("Socket is closed = " + serverSocket.isClosed()); 



     BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

     String str = rd.readLine(); 
     System.out.println("Recieved: " + str); 
     rd.close(); 



     InputStream is = connection.getInputStream(); 

     int bufferSize = connection.getReceiveBufferSize(); 

     FileOutputStream fos = new FileOutputStream("C:/" + str); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 


     byte[] bytes = new byte[bufferSize]; 

     int count; 

     while ((count = is.read(bytes)) > 0) { 
      bos.write(bytes, 0, count); 
     } 

     bos.flush(); 
     bos.close(); 
     is.close(); 
     connection.close(); 
     serverSocket.close(); 


    } 
} 

這裏是客戶端代碼:

public class TheClient { 

    public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class. 
     Socket socket = null; 
     String host = "127.0.0.1"; 

     socket = new Socket(host, 1991); 

     // Get the size of the file 
     long length = file.length(); 
     if (length > Integer.MAX_VALUE) { 
      System.out.println("File is too large."); 
     } 

     BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
     wr.write(file.getName()); 
     wr.newLine(); 
     wr.flush(); 

     byte[] bytes = new byte[(int) length]; 
     FileInputStream fis = new FileInputStream(file); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); 

     int count; 

     while ((count = bis.read(bytes)) > 0) { 
      out.write(bytes, 0, count); 
     } 


     out.flush(); 
     out.close(); 
     fis.close(); 
     bis.close(); 
     socket.close(); 
    } 
} 

回答

2
  1. 您正在閱讀的所有數據之前在服務器端過早關閉BufferedReader。這基本上關閉了連接。
  2. 對於非字符流(如二進制圖像數據),不應使用ReaderWriter。而且您不應該將BufferedReader與任何其他流封裝器混合使用相同的流,因爲它可以在填充緩衝區時讀取儘可能多的數據。
+0

1.嗨,即時通訊相當新的套接字的東西,所以你可以告訴我應該怎麼做? 2.這是多麼糟糕的錯誤? –

+0

@RohitMalish 1.顯然,如果您期待更多數據被讀取,您不應該關閉流。 2.它可能導致意想不到的行爲。我建議遵循一些關於Java套接字的初學者教程。 – pingw33n