我正在尝试在 java 上编写客户端和服务器端。服务器端没问题(检查了几个客户端)。
所以,问题出在客户端。我为它分配内存bytearray
、读取BufferedInputStream
和写入bytearray
。然后从bytearray
FileOutputStream 写入。一切正常,但可用空间bytearray
被 NULL 填充,因此接收到的文件不正确(例如图像)。
我发现了该问题的两个决定:
- 读到
bytearray
文件末尾(但我不知道文件末尾在哪里) BufferedInputStream
从to读取FileInputStream
,但它不起作用:
我实际上需要接收头和文件。将标头输出到控制台并将文件写入光盘。
完整来源
public class SClient {
private static int bufferSize = 8192;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter the address:");
BufferedReader bufferRead = new BufferedReader
(new InputStreamReader(System.in));
try {
String address = bufferRead.readLine();
System.out.println("Enter the extention of receiving file:");
String fileExt = bufferRead.readLine();
// TODO code application logic here
Socket socket = new Socket(address,4040);
BufferedInputStream bis = new BufferedInputStream
(socket.getInputStream());
BufferedOutputStream bout = new BufferedOutputStream
(socket.getOutputStream());
System.out.println("Enter the request:");
String message = bufferRead.readLine();// GET /index.html HTTP/1.0
System.out.println("Header read");
if(message!=null){
bout.write(message.getBytes());
}
FileOutputStream fout = new FileOutputStream("out"+fileExt);
String s1 = "\r\n\r\n";
bout.write(s1.getBytes());
bout.flush();
System.out.println("Header sent");
byte[] res = new byte[bufferSize];
int got;
while((got = bis.read(res))!=-1){
fout.write(res,0,got);
}
fout.close();
bout.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器端源码:
String endLine = "\r\n";
File f = new File(fileName);
FileInputStream fstream;
fstream = new FileInputStream(f);
response = "HTTP/1.0 200 OK" + endLine;
header = "Content-type: "+ contentType + endLine + "Content-length: " + f.length() + endLine + endLine;
bout.write(response.getBytes());
bout.write(header.getBytes());
while(fstream.read(buffer) != -1) {
bout.write(buffer);
}
System.out.println("Message sent");
bout.flush();
socket.close();