2013-10-25 96 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类。