java - IndexOutOfBoundException when reading a file -
i working on tftp server application. managed process successful file transfer server client other way around bugged.
client instead of transmitting entire file terminated whit compiler returning no errors. debugger shows iobe exception on marked code referring array out of range.
the whole transfer process goes so:
- client transmits file name , requested operation wrq - write request
- server received packet , determines operation if wrq gives new file appropriate name.
- server starts executing receivedata() until gets packet < 512 indicationg eot
- client keeps transferring data read file.
key code:
client:
private void sendwrq() throws exception { string rrq = "wrq-" + data; outgoingdata = rrq.getbytes(); datagrampacket output = new datagrampacket(outgoingdata, outgoingdata.length, serveraddress, serverport); clientsocket.send(output); //thread.sleep(50); senddata(); } byte outgoingdata = new byte[512]; private void senddata() throws exception { datagrampacket datatransfer = new datagrampacket(outgoingdata, outgoingdata.length, serveraddress, serverport); inputstream fis = new fileinputstream(new file(data)); int x; while((x = fis.read(outgoingdata,0,512)) != -1) // << debugged gives iobe { datatransfer.setlength(x); clientsocket.send(datatransfer); thread.sleep(5); } fis.close(); }
server:
private void listen() throws exception { datagrampacket inctransfer = new datagrampacket(incomingdata, incomingdata.length); serversocket.receive(inctransfer); clientaddress = inctransfer.getaddress(); clientport = inctransfer.getport(); string output = new string(inctransfer.getdata()); if(output.substring(0, 3).equals("rrq")) { file test = new file(output.substring(4)); responsedata = output.substring(4); if(test.exists()) { sendresponse("y"); } else { sendresponse("n"); } } else if (output.substring(0, 3).equals("wrq")) { file test = new file(output.substring(4)); if(test.exists()) { calendar cal = calendar.getinstance(); simpledateformat prefix = new simpledateformat(date_format); string date = prefix.format(cal.gettime()).tostring(); responsedata = date + output.substring(4); receivedata(); } else { responsedata = output.substring(4); receivedata(); } } } private void receivedata() throws exception { datagrampacket receivedata = new datagrampacket(incomingdata, incomingdata.length); outputstream fos = new fileoutputstream(new file(responsedata)); while(true) { serversocket.receive(receivedata); if(receivedata.getlength() == 512) { fos.write(receivedata.getdata()); } else { fos.write(receivedata.getdata(), receivedata.getoffset(), receivedata.getlength()); break; } } fos.close(); }
the way can happen if offset or length parameters violate constraints specified inputstream.read(byte[], int, int)
; in case buffer isn't 512 bytes long. there's no need specify 2nd nd third parameters in case, omit them, becomes read(buffer, 0, buffer.length)
internally, can't wrong.
Comments
Post a Comment