0

我有一个服务器客户端文件传输程序,它在 java 中运行良好。但我复制了它并将文件位置 d:/ 更改为 environm .....

问题是文件大小小于发送一个,因此它显示为损坏..任何想法。

服务器端

public class Server 
{
// create socket
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
while(true)
{
  ServerSocket servsock = new ServerSocket(13000);   
  System.out.println("Main Waiting...");
  Socket socket = servsock.accept();
  System.out.println("Accepted connection : " + socket);
 DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

  long filesize = new Long(in.readLong());
  System.out.println("received Size:"+filesize);
  // read file name
  String fname=in.readUTF();

  System.out.println("server : file name: "+fname);
  String prefix=fname.substring(0,fname.lastIndexOf('.')).trim();
  String suffix=fname.substring(fname.lastIndexOf('.'),fname.length()).trim();          
  String file = prefix + suffix;   
  System.out.println("received name:"+file);

        File f=new File("F:/Users/achu/Desktop/"+ file);// changed this in android
    f.createNewFile();
    // receive file
    byte [] mybytearray  = new byte [(int)(filesize)];
    InputStream is = socket.getInputStream();
    FileOutputStream fos = new FileOutputStream(f);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;
    do {
                   System.out.println("current"+current);
       bytesRead =
       is.read(mybytearray, current, (mybytearray.length-current));
       if(bytesRead >= 0) current += bytesRead;
    } while(current<filesize && bytesRead >-1);
    bos.write(mybytearray, 0 , current);
    bos.flush();
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    bos.close();
    is.close();
  socket.close();
  servsock.close();
  } 

    }

客户端

public class  Client
{ 
Socket socket=new Socket("101.59.43.58",13000); 
System.out.println("Connectedddd"); 

DataOutputStream out = new DataOutputStream(socket.getOutputStream());

File file = new File("d:/my.pdf");

out.writeLong(file.length());
out.flush();    


out.writeUTF(file.getName());


byte [] mybytearray  = new byte [(int)file.length()];  
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);                         

System.out.println("Send:"+mybytearray.length);
OutputStream ous = socket.getOutputStream();
System.out.println("Sending...");
ous.write(mybytearray,0,mybytearray.length);
ous.flush();
bis.close();
ous.close();
System.out.println("closing socket...");            
socket.close();

}
4

0 回答 0