views:

179

answers:

3

Hi,

I am trying to send a file through a java socket and receive it through another. However, this happens:

Send Content:

/* This is simply a file to transfer */

Received:

so basically I cannot escape the received content on stack overflow. It is basically a bunch of unreadable bytes (about 32 bytes worth) and then the message I sent.

OutputStream os = sock.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(mybytearray);
oos.flush();
oos.close();

And for the client:

BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
FileOutputStream fos = new FileOutputStream("newfile.java");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
bos.write(mybytearray, 0 , current);
bos.flush();
bos.close();
sock.close();
+1  A: 

It would help to see the code, but what you've got there looks like basic random data. Some things to check:

  1. What type is the receive buffer?
  2. How many characters do you seem to be sending and receiving?
  3. Are you sure your print statement on the receive end is pointing at the right place?
Charlie Martin
1. receive buffer is a byte[]2. I want to send 39 bytes and receive 663. I think the receive is pointing to the right place. The file is created, it just has too many 66 bytes instead of 39. I'm not sure if this is what you mean.
Andy
Yup. Note that you have just about twice as many bytes received as you expect; this should make you wonder about matching types. Now, consider what ObjectOutputStream actually does: it *encodes* an object so it can be recovered. When you send your data as an ObjectOutputStream, Java will encode it to be an array. See http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.htmlWhat you're getting is the "serialized" form of a byte array.
Charlie Martin
haha thanks, I was so focused on the client code I didn't see i was sending a object output stream.
Andy
+1  A: 

Why go through ObjectOutputStream? Either use the OutputStream directly through the write method, or choose for instance DataOutputStream if you find it neccessary.

Besides, you should not use the Reader classes for transferring binary data. From the api of Reader:

Abstract class for reading character streams.


A complete "send file over socket" example can be found here:

Transfer a file via Socket.

Key server-side code:

  OutputStream os = sock.getOutputStream();
  System.out.println("Sending...");
  os.write(mybytearray,0,mybytearray.length);
  os.flush();
  sock.close();

Key client-side code:

bytesRead = is.read(mybytearray,0,mybytearray.length);
aioobe
A: 

This doesn't make any sense. If you use an ObjectOutputStream you have to use an ObjectInputStream to read it. If you want to use a Reader to read it you have to use a Writer to write it.

EJP