| Author |
File Transfer-Error
|
Roshini Sridharan
Ranch Hand
Joined: Jan 16, 2001
Posts: 143
|
|
Problem in File Read/Write using DatagramSocket/Packet. How to use Datagram Socket to transmit binary data. Following contains a piece of code that i use to transmit text data and the code works fine for (textual data) and doesn't work fine for (.zip/.jpg) file format. ----------------------------------------------------------- Client Code FileOutputStream fos = new FileOutputStream(".\\temp\\"+filename,false); boolean read = true; int loop = 1; DatagramPacket dp =null; while(read) { byte buffer[] = new byte[size]; dp = new DatagramPacket(buffer,0,buffer.length); System.out.println("Inside Receive " + loop); Thread.sleep(10); ds.receive(dp); String str = new String(dp.getData()); buffer = str.getBytes(); int len = dp.getLength(); int offset = dp.getOffset(); System.out.println("Size " + len + "\tOffset " + offset); fos.write(buffer, offset, len); fos.flush(); if(len<size){ read = false; break; } loop++; } fos.close(); ----------------------------------------------------------- Server Code for(int i =1;i<=loop;i++) { byte buffer[] = new byte[size]; int read = fis.read(buffer,0,buffer.length); System.out.println(i + " Read : " + read + " B " + buffer.length); dp = new DatagramPacket(buffer,0,read,InetAddress.getByName(clientip),clientport); int offset = dp.getOffset(); int len = dp.getLength(); System.out.println("Size " + len + "\tOffset " + offset); dp.setLength(len); ds.send(dp); Thread.sleep(50); } ----------------------------------------------------------- Can anybody suggest, how to change the code to support both ascii and binary data read/write. Thanx in Advance Regards S.Roshini
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24054
|
|
Well, it's these two lines: that are going to corrupt binary data when it's received. Many raw byte values will have special meanings when interpreted as characters -- 0 is going to be especially troublesome. Replace these two lines with a simple "buffer = dp.getData()", and you should be in reasonable shape.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Roshini Sridharan
Ranch Hand
Joined: Jan 16, 2001
Posts: 143
|
|
Hello Sir, Thanx a lot for ur timely and valuable reply. I got it working fine. Regards Roshini.S
|
 |
 |
|
|
subject: File Transfer-Error
|
|
|