java - Sending file with custom attributes over a network -
i want create client-server program allows client send file server along information file (sender name, description, etc.).
the file potentially quite large either text, picture, audio or video file, , because of not want have read whole file byte array before sending, rather read file in blocks, sending them on network , allowing server append blocks file @ it's end.
however faced problem of how best send file along few bits of information file itself. @ minimum send sender's name , description both of input client program user, may change in future should flexible.
what way of doing allow me "stream" file being sent rather reading in whole , sending?
sockets natively streams of bytes shouldn't have problem there. suggest have protocol looks this.
this allow send arbitrary properties long total length less 64 kb. followed file can 63-bit length , sent block @ time. (with buffer of 8 kb)
the socket can used send more files if wish.
dataoutputstream dos = new dataoutputstream(socket.getoutputstream()); properties fileproperties = new properties(); file file = new file(filename); // send properties stringwriter writer = new stringwriter(); fileproperties.store(writer, ""); writer.close(); dos.writeutf(writer.tostring()); // send length of file dos.writelong(file.length()); // send file. byte[] bytes = new byte[8*1024]; fileinputstream fis = new fileinputstream(file); int len; while((len = fis.read(bytes))>0) { dos.write(bytes, 0, len); } fis.close(); dos.flush();
to read
datainputstream dis = new datainputstream(socket.getinputstream()); string propertiestext = dis.readutf(); properties properties = new properties(); properties.load(new stringreader(propertiestext)); long lengthremaining = dis.readlong(); fileoutputstream fos = new fileoutputstream(outfilename); int len; while(lengthremaining > 0 && (len = dis.read(bytes,0, (int) math.min(bytes.length, lengthremaining))) > 0) { fos.write(bytes, 0, len); lengthremaining -= len; } fos.close();
Comments
Post a Comment