c# - TCP File Transfer - Few bytes error -
i working on c# program allows user send file on network , reassemble @ other end. working fine apart few bytes being misplaced int destination leaving not quite same file started as. (corrupting images example). edit: @ least when it's on computer noticed error can solved having client wait 1 second before starting read stream, gives idea client gets end of stream , reads else instead. idea how fix in better way waiting second other computers don't know if that'll work. code server follows:
tcplistener listener = new tcplistener(13); listener.start(); filestream inputstream = file.openread(loadlocation.text);//loadlocation being text box file path fileinfo f = new fileinfo(loadlocation.text); int size = unchecked((int)f.length);//get's file size in bytes int csize = size / 4096;//get's size in chunks of 4kb; statuslabel.text = "waiting connection..."; tcpclient client = listener.accepttcpclient(); statuslabel.text = "connection accepted."; networkstream ns = client.getstream(); byte[] bytesize = bitconverter.getbytes(size);//sends number of bytes expect on network try { ns.write(bytesize, 0, bytesize.length); byte[] temp = new byte[4096]; (int = 0; < csize; i++) { inputstream.read(temp, 0, 4096); ns.write(temp, 0, 4096); } byte[] end = new byte[size % 4096]; inputstream.read(end, 0, size % 4096); ns.write(end, 0, size % 4096); ns.close(); inputstream.close(); client.close(); done = true; statuslabel.text = "done!"; } catch (exception a) { console.writeline(a.tostring()); } listener.stop();
the client code follows:
try { filestream outputstream = file.openwrite(savelocation.text); tcpclient client = new tcpclient("127.0.0.1", 13); networkstream ns = client.getstream(); byte[] bytetime = new byte[sizeof(int)]; int bytesread = ns.read(bytetime, 0, sizeof(int)); int size; size = bitconverter.toint32(bytetime, 0); int csize = size / 4096; byte[] temp = new byte[4096]; (int = 0; < csize; i++) { ns.read(temp, 0, 4096); outputstream.write(temp, 0, 4096); } byte[] end = new byte[size % 4096]; ns.read(end, 0, size % 4096); outputstream.write(end, 0, size % 4096); ns.close(); outputstream.close(); client.close(); statuslabel.text = "done!"; } catch (exception a) { console.writeline(a.tostring()); }
i know tcp guarantees order of delivery , such have no idea possibly causing problem output file. other note worthy part each time, corruption different example when transferring image there large mark @ different point on image.
your code should take account, networkstream
(and tcp sockets
in general) not return full number of bytes requested.
microsoft writes:
the read operation reads data available, number of bytes specified size parameter.
add outer loop around read operations ensure buffer filled. more error handling advisable.
perhaps, can inspiration similar question+answer. shows how such outer loop can like.
Comments
Post a Comment