How to Send Multiple File from Server to Client
Hi..
i am just a newbie here,
i want send multiple file (ex.100 files) from server to client using loop.
but the client side just get only 1 file and the connection direct to close.
this is make me confused.
plis help me :
Server Code :
Code:
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {
DataInputStream in;
DataOutputStream out;
int i =1;
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
i++;
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
File myFile = new File ("C:/Test/namafile-"+i+".txt");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}
Client Code :
Code:
import java.net.*;
import java.io.*;
public class Client{
public static void main(String[] args) throws UnknownHostException, IOException{
int i=0;
while(true){
int filesize=6022386;
DataOutputStream out = null;
DataInputStream in =null;
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
try{
i++;
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:/Hasil/"+i+"-");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
}
catch(EOFException e){
e.printStackTrace();
}
sock.close();
}
}
}
thanks for moderator..please help me to get client code can receive multiple file from server
the client code can receive first file, and then exception show
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at java.io.BufferedOutputStream.write(BufferedOutputS tream.java:111)
at javasocket.Client.ClientSet(Client.java:55)
at javasocket.Client.main(Client.java:72)
Java Result: 1