java - Client-server application file transfer -
i trying design client-server application, this: user connects server , when authentication ok server send user files. problem files written in single file (with method).
here code:
the function transfers file
public void processfile(int id, dataoutputstream ostream, socket socket, int tip){ string filename; if(tip==0){ filename="file"+integer.tostring(intrebari[id])+".txt"; }else{ filename="image"+integer.tostring(intrebari[id])+".jpg"; } byte[] buffer=null; int bytesread = 0; fileinputstream file=null; try { file = new fileinputstream(filename); buffer = new byte[socket.getsendbuffersize()]; while((bytesread = file.read(buffer))>0) { ostream.write(buffer,0,bytesread); } file.close(); } catch (ioexception ex) { system.out.println(ex); } }
and function choose file have send
private void send(int id) throws ioexception { os.writebytes("sendfile" + id+"\n"); system.out.println("sendfile" + id); generatedfiles.processfile(id, os, comunicare, 0); if (generatedfiles.imagini[id] == 1) { os.writebytes("sendimage" + id+"\n"); try { thread.sleep(1000); } catch (interruptedexception ex) { logger.getlogger(clientthread.class.getname()).log(level.severe, null, ex); } system.out.println("sendimage" + id); generatedfiles.processfile(id, os, comunicare, 1); } }
i have mention os
dataoutputstream
, comunicare
socket
type.
i think problem combine writebytes
write
. can me problem? how can make server , client receive both files , messages?
i this:
server -send command server -send file client -confirms file sucessfull
server -send command server -send file client -confirms file sucessfull ...
like this...supose have socket client, you...
socket.getoutputstream.write("file: somefile.bin, size: 872973493\r\n".getbytes("choose encoding")) socket.getoutputstream.flush(); (you need flush if expecting server string response like: ok send me file, im ready, otherwise no need too) client reads , see file , has bytes size, starts reading socket.getinputstream untill gets length of file expected. after clients confirm recived file
then server can send file, instead of file, use image: or want. have read message client side see if file or image
here functions might you:
public static void readinputstreamtofile(inputstream is, fileoutputstream fout, long size, int buffersize) throws exception { byte[] buffer = new byte[buffersize]; long curread = 0; long totalread = 0; long sizetoread = size; while(totalread < sizetoread) { if(totalread + buffer.length <= sizetoread) { curread = is.read(buffer); } else { curread = is.read(buffer, 0, (int)(sizetoread - totalread)); } totalread = totalread + curread; fout.write(buffer, 0, (int) curread); } } public static void writefileinputstreamtooutputstream(fileinputstream in, outputstream out, int buffersize) throws exception { byte[] buffer = new byte[buffersize]; int count = 0; while((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } }
Comments
Post a Comment