tcp - Java file not working when sent over a network -
so implementing client , socket java. wanted send huge files on tcp through sockets , able send files problem files on other end either not complete or not working. have checked bits being transfered error.
client side:
socket sock = new socket("127.0.0.1", 1056); byte[] mybytearray = new byte[1024]; inputstream = sock.getinputstream(); fileoutputstream fos = new fileoutputstream("abc.mp3"); bufferedoutputstream bos = new bufferedoutputstream(fos); int bytesread = is.read(mybytearray, 0, mybytearray.length); int len = 0; while((len = is.read(mybytearray)) != -1) { bos.write(mybytearray, 0, len); system.out.println("sending"); } bos.close(); sock.close();
server side:
serversocket ss = new serversocket(1056); while (true) { socket s = ss.accept(); printstream out = new printstream(s.getoutputstream()); bufferedreader in = new bufferedreader(new inputstreamreader(s.getinputstream())); string info = null; string request = null; system.out.println("sending"); string filename = "abc.mp3"; file fi = new file(filename); inputstream fs = new fileinputstream(fi); int n = fs.available(); byte buf[] = new byte[1024]; out.println("content_length:" + n); out.println(""); while ((n = fs.read(buf)) >= 0) { out.write(buf, 0, n); system.out.println("sending"); } out.close(); s.close(); in.close(); }
when connected via tcp create network stream can read , write in, similar other streams worked with. writing large amount of data stream not idea, suggest break selected file smaller packets in each packet length 1024 bytes (1kb) , send packets server. sendtcp function follows:(i have used windows forms make things more obvious)
public void sendtcp(string m, string ipa, int32 portn) { byte[] sendingbuffer = null tcpclient client = null; lblstatus.text = ""; networkstream netstream = null; try { client = new tcpclient(ipa, portn); lblstatus.text = "connected server...\n"; netstream = client.getstream(); filestream fs = new filestream(m, filemode.open, fileaccess.read); int noofpackets = convert.toint32 (math.ceiling(convert.todouble(fs.length) / convert.todouble(buffersize))); progressbar1.maximum = noofpackets; int totallength = (int)fs.length, currentpacketlength, counter = 0; (int = 0; < noofpackets; i++) { if (totallength > buffersize) { currentpacketlength = buffersize; totallength = totallength - currentpacketlength; } else currentpacketlength = totallength; sendingbuffer = new byte[currentpacketlength]; fs.read(sendingbuffer, 0, currentpacketlength); netstream.write(sendingbuffer, 0, (int)sendingbuffer.length); if (progressbar1.value >= progressbar1.maximum) progressbar1.value = progressbar1.minimum; progressbar1.performstep(); } lblstatus.text=lblstatus.text+"sent "+fs.length.tostring()+" bytes server"; fs.close(); } catch (exception ex) { console.writeline(ex.message); } { netstream.close(); client.close(); } }
as can see, tcp client , network stream being constructed , network connection initiated. after opening selected file according buffer size 1024 bytes, number of packets going sent calculated. there 2 other variables currentpacketlength , totallength. if total length of selected file more buffer size currentpacketlength set buffer size, otherwise why send empty bytes, currentpacketlength set total length of file. after that, subtract current total length, can total length showing total amount of data has not been sent yet. rest pretty straight forward, reading data file stream , writing sendingbuffer according currentpacketlength , writing buffer network stream.
at server side, application listening incoming connection:
public void receivetcp(int portn) { tcplistener listener = null; try { listener = new tcplistener(ipaddress.any, portn); listener.start(); } catch (exception ex) { console.writeline(ex.message); } byte[] recdata = new byte[buffersize]; int recbytes; (; ; ) { tcpclient client = null; networkstream netstream = null; status = string.empty; try { string message = "accept incoming file "; string caption = "incoming connection"; messageboxbuttons buttons = messageboxbuttons.yesno; dialogresult result; if (listener.pending()) { client = listener.accepttcpclient(); netstream = client.getstream(); status = "connected client\n"; result = messagebox.show(message, caption, buttons); if (result == system.windows.forms.dialogresult.yes) { string savefilename=string.empty; savefiledialog dialogsave = new savefiledialog(); dialogsave.filter = "all files (*.*)|*.*"; dialogsave.restoredirectory = true; dialogsave.title = "where want save file?"; dialogsave.initialdirectory = @"c:/"; if (dialogsave.showdialog() == dialogresult.ok) savefilename = dialogsave.filename; if (savefilename != string.empty) { int totalrecbytes = 0; filestream fs = new filestream (savefilename, filemode.openorcreate, fileaccess.write); while ((recbytes = netstream.read (recdata, 0, recdata.length)) > 0) { fs.write(recdata, 0, recbytes); totalrecbytes += recbytes; } fs.close(); } netstream.close(); client.close(); } } } catch (exception ex) { console.writeline(ex.message); //netstream.close(); } } }
a tcp listener created , starts listening specified port. again buffer size set 1024 bytes. tcp listener can pre check see if there connections pending before calling accepttcpclient method. returns true if there pending connections. method way of avoiding socket being blocked. before reading network stream, message box asks if want accept incoming connection, savefiledialog opened, , when enter file name plus extension, file stream constructed , start reading network stream , writing file stream. create thread in code , run receiving method in created thread. have sent more 100 mb files in lan application.
for more details, check article.
Comments
Post a Comment