我正在尝试使用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 :(得分:1)
Reader和Writer类传输文本流,可能会破坏二进制数据。改为使用InputStream和OutputStream类。