java - Send multiple files using socket -
i'm trying send multiple files client server using socket when click upload button adds 1 file , second click adds second. code:
client
void sendfile (string st, string na) throws ioexception{ socket sock = new socket("127.0.0.1", 1112); //objectoutputstream out = new objectoutputstream(sock.getoutputstream()); //outstream.writeobject("test message #"); //outstream.flush(); //fileinputstream fi = null; try { // todo add handling code here: fileinputstream fi = new fileinputstream(st); byte [] buffer = new byte[fi.available()]; fi.read(buffer); objectoutputstream out = new objectoutputstream(sock.getoutputstream()); out.writeobject(buffer); out.flush(); out.close(); //outstream.writeobject(buffer); write.println("send:file: " + na); write.flush(); } catch (filenotfoundexception ex) { logger.getlogger(add_book.class.getname()).log(level.severe, null, ex); } catch (ioexception ex) { logger.getlogger(add_book.class.getname()).log(level.severe, null, ex); } catch (exception ex) { system.out.println("error connecting server"); } sock.close(); } `
call method:
sendfile(coverpath,covername); sendfile(bookpath,bookname);
server
public class uploadserver implements runnable { @override public void run() { clientoutputstreams = new arraylist(); users = new arraylist(); try { serversocket serversocket = new serversocket(1112); while (true) { socket clientsocket = serversocket.accept(); objectoutputstream oos = new objectoutputstream(clientsocket.getoutputstream()); = clientsocket.getinputstream(); thread listener = new thread(new uploadhandler(clientsocket)); listener.start(); textarea.append("request upload. \n"); ss = clientsocket; } } catch (exception ex) { textarea.append("error making connection. \n"); } } } public class uploadhandler implements runnable { objectinputstream inputs; objectinputstream input; bufferedreader reader; objectinputstream ois; socket sock; byte[] abyte = new byte[1]; int bytesread; public uploadhandler(socket clientsocket) { try { sock = clientsocket; inputs = new objectinputstream(sock.getinputstream()); //input = new objectinputstream(sock.getinputstream()); } catch (exception ex) { textarea.append("unexpected error... \n"); } } @override public void run() { try { byte [] buffer = (byte[]) inputs.readobject(); fileoutputstream fi = new fileoutputstream("uploads\\"+name); fi.write(buffer); system.out.println("done"); } catch (ioexception ex) { logger.getlogger(server.class.getname()).log(level.severe, null, ex); } catch (classnotfoundexception ex) { logger.getlogger(server.class.getname()).log(level.severe, null, ex); } } }
Comments
Post a Comment