1
我试图写一个非常简单的客户端服务器应用程序,客户端发送文本文档.docx格式和服务器接收,简单地。Java客户端 - 服务器发送文件流
我的问题是,该文件(mupp.docx)收到损坏,根据字: http://www.ladda-upp.se/files/2014/b126506.jpg
林不知道我哪里错在这里。我不确定的事情是:
*应该将最后一个读数写入文件中,其中fis.read(b)返回-1。到客户端的输出流?
*我是否过频冲洗?
*我有不正确的字节大小[] b?
我试着围绕if(x == - 1)break;在两个方案中都没有成功。我不知道什么是错的:/你呢?
public class FileSender{
public static void main(String ar[])throws Exception{
Socket clientSocket=new Socket("127.0.0.1",1234);
System.out.println("connected");
OutputStream out=clientSocket.getOutputStream();
FileInputStream fis=new FileInputStream("lupp.docx");
int x=0;
byte[] b = new byte[256];
while(true){
x=fis.read(b);
if(x==-1)break;
out.write(b);
out.flush();
}
fis.close();
out.close();
}
}
public class FileReceiver{
public static void main(String ar[])throws Exception{
ServerSocket ss=new ServerSocket(1234);
Socket clientSocket=ss.accept();
InputStream in=clientSocket.getInputStream();
FileOutputStream fos=new FileOutputStream("mupp.docx");
int x=0;
byte[] b = new byte[256];
while(true){
x=in.read(b);
if(x==-1)break;
fos.write(b);
fos.flush();
}
in.close();
fos.close();
}
}
是的,它做到了!但是...为什么它现在工作? – user3660678 2014-11-22 13:16:40
这是因为我们并不总是阅读整个缓冲区。 x表示读取的字节数。 – gashu 2014-11-22 13:19:14