2013-10-25 269 views
0

我試圖使用SSL套接字工廠傳輸二進制文件。在java中通過SSL套接字傳輸類文件

到目前爲止,它正確地傳輸大部分文件,但接收的文件已損壞。

所以我想知道如果它的編碼問題或別的東西?

客戶端代碼:

  SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); 
     SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port); 

     InputStream inputstream = System.in; 
     InputStreamReader inputstreamreader = new InputStreamReader(inputstream); 
     BufferedReader fr = new BufferedReader(new FileReader(fileName)); 

     OutputStream outputstream = sslsocket.getOutputStream(); 
     OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream); 
     BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter); 

     String string = null; 
     bufferedwriter.write("file;" + fileName + '\n'); 
     while ((string = fr.readLine()) != null) {    
      bufferedwriter.write(string + '\n'); 
      bufferedwriter.flush(); 
     } 

     bufferedwriter.write("end"); 
     bufferedwriter.flush(); 

服務器代碼:

 SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory 
       .getDefault(); 
     SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory 
       .createServerSocket(port); 
     SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); 

     InputStream inputstream = sslsocket.getInputStream(); 
     InputStreamReader inputstreamreader = new InputStreamReader(
       inputstream); 
     BufferedReader bufferedreader = new BufferedReader(
       inputstreamreader); 

     OutputStream outputstream = sslsocket.getOutputStream(); 
     OutputStreamWriter outputstreamwriter = new OutputStreamWriter(
       outputstream); 
     BufferedWriter bufferedwriter = new BufferedWriter(
       outputstreamwriter); 

     String string = null; 
     boolean file = false; 
     FileWriter f = null; 
     PrintWriter pw = null; 

     while ((string = bufferedreader.readLine()) != null) { 
      String[] splitRead = string.split(";"); 
      if (splitRead[0].trim().equals("[FILE]")) { 
       f = new FileWriter(splitRead[1]); 
       pw = new PrintWriter(f, true); 
       file = true; 
      } else if (file) { 
       if (splitRead[0].equals("end")) { 
        file = false; 
        pw.close(); 
       } else { 
        pw.println(string); 
       } 
      } else { 
       System.out.println(string); 
       System.out.flush(); 
      } 
     } 
+0

如果您嘗試傳輸二進制數據,那麼您爲什麼要發送字符串?您需要將二進制數據編碼爲字符串(例如Base64)或發送實際字節。 – chrylis

+0

另外,如果你使用readLine,那麼你顯然閱讀文本 –

回答

1

的Reader和Writer類傳輸文本流,並且將可能損壞二進制數據。改用InputStream和OutputStream類。