我正在编写一些代码
我的客户端代码是
客户端
import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[])
{
try
{
int len=args.length;
if(len== 0)
{
System.out.println("Invalid Number of Arguements");
throw new Exception();
}
else
{
int i=0;
while(i<len)
{
Socket s=new Socket("localhost",2222);
File f=new File(args[i++]);
if(f.exists())
{
OutputStream os=s.getOutputStream();
FileInputStream fr=new FileInputStream(f);
s.setSendBufferSize(fr.available());
byte data[]=new byte[fr.available()];
fr.read(data);
os.write(data);
os.flush();
os.close();
System.out.println("Sending file : "+f.getName()+" with size "+data.length);
fr.close();
}
else
{
System.out.println("File : "+args[i++]+" doesn't exist.");
}
s.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
用于服务器端
import java.net.*;
import java.io.*;
import java.util.Date;
public class Server
{
public static final String dir_to_store_files="c:\\myfiles\\";
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(2222);
ss.setReceiveBufferSize(51200);
ss.setReuseAddress(true);
Socket s=null;
while( (s=ss.accept()) != null)
{
new Thread(new ServerThreads(s,dir_to_store_files)).start();
s=null;
}
ss.close();
}
}
class ServerThreads implements Runnable
{
private static int fileNounce=0;
Socket s;
String directory;
ServerThreads(Socket s,String directory)
{
this.s=s;
this.directory=directory;
}
public void run()
{
try
{
InputStream is=s.getInputStream();
File f=new File(directory+"\\NewFile-"+fileNounce+".txt");
while(f.exists())
{
fileNounce++;
f=new File(directory+"\\NewFile "+fileNounce+".txt");
}
fileNounce++;
f.createNewFile();
FileOutputStream fos=new FileOutputStream(f);
byte data[]=new byte[is.available()];
System.out.print(is.available()+ " bytes are received from "+s.getRemoteSocketAddress());
is.read(data);
System.out.println("\t\tCreating file : "+f.getAbsolutePath()+" at : "+new Date()+" of size : "+data.length);
is.close();
fos.write(data);
fos.flush();
fos.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
问题:服务器无法正确获取文件意味着有时新文件创建为零大小(无数据)。例如,我已检查过发送239个c文件 java Client * c 服务器正在接收随机数量的文件(范围180-235) 甚至它收到的一些文件都是零大小。
答案 0 :(得分:2)
fr.available()不是你想象的那样....你想要File.length(),以及一个用于读取文件字节的循环发送到服务器......
is.available()也错了..。考虑客户端,看起来像:
byte[] buffer = new byte[4096];
int len = 0;
while ((len = fr.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}