Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to read binary data from socket

 
ram budigi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The lenght coming from socket varies for each request. The data coming from socket is binary data. I am using the following code and it taking more than 45 seconds to read the binary data. How do I read the data fast?
Any help on how to read the binary data fast from socket ?

try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.write(request);
String line = reader.readLine();
sbResponse = new StringBuffer();
while(line != null) {
sbResponse.append(line).append("\n");
line = reader.readLine();
}
}catch (IOException e) { }
 
Joe Ess
Bartender
Pie
Posts: 9265
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a bad idea to use a Reader to read binary data. Readers are used to read encoded text and will trim the data to match the default encoding.
As for the amount of time to move data, that depends on how much you are moving and the speed of your connection. There's good information on improving IO throughput in the Java Platform Performance online book.
 
ram budigi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tahnks for your quick response. Could you provide some sample code to read the entire data from stream into a String or StringBuffer.

InputStream inStream = new BufferedInputStream(socket.getInputStream());
OutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
outStream.write(request);
outStream.flush();
byte[] array = new byte[100];
inStream.read(array,0,100);
String str = new String(array);
System.out.println("str =="+str);
 
ram budigi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is taking more than 40 seconds to read response from socket client. If I use streams or readers it is taking same time.

InputStream inStream = new BufferedInputStream(socket.getInputStream());
OutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
outStream.write(request);
outStream.flush();
byte[] array = new byte[100];
while(true) {
int a = inStream.read(array,0,100);
if(a == -1) break;
str = new String(array);
sbResponse.append(str);
array = new byte[100];
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can play with larger and smaller buffers. If the stream is pretty big go for 16k or 64k and see what happens.

Are you sure it's not just taking the other end 40 seconds to send the data?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic