i'm writing some code where
My client code is
for Client Side
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();
}
}
}
for Server Side
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();
}
}
}
The Problem : Server is unable to get files correctly means sometimes the new files are created with zero size(no data).For example i have checked with sending 239 c-files using java Client *c Server is receiving random number of files (in range 180-235) Even some files which it receives are of zero size.
fr.available() is not what you think it is.... You want File.length(), and a loop for reading the file bytes to send to the server...
is.available() is also wrong .. .consider a client side that looks like:
byte[] buffer = new byte[4096];
int len = 0;
while ((len = fr.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}