Transfer Java object via Sockets, Byte []


Would you take a look over this?:

This is my client:

try {
        Socket socket = new Socket("", 3000);
        OutputStream out = socket.getOutputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        byte[] bytes = baos.toByteArray();
        catch (IOException e) {
            // TODO Auto-generated catch block

This is my server:

int port = 3000;
        try {
        ServerSocket clientConnect = new ServerSocket(port);
        System.out.println("SimpleServer running on port" + port);
        Socket clientSock = clientConnect.accept();
        InputStream is = clientSock.getInputStream();

    byte[] buffer = new byte[1024];
    int read =;

    ObjectInputStream ois = new ObjectInputStream(is);
    MP3[] songs = (MP3[])ois.readObject();  


    // HTML erzeugen
    Website site = new Website("index2.html",songs);

    } catch (Exception e) {
    System.out.println (e);

It ain't work. I don't get any exceptions but the Website-Constructor isn't called.

You assume that the whole byte array is read in just one call to read(), and has a length of exactly 1024 bytes. That's not the case (unless you're extremely lucky). Moreover, your ObjectInputStream is wrapping the InputStream from which you have already read the bytes (or some of the bytes) constituting the message. And also, the bytes written by the sender are not flushed.

Don't ignore the result of the call to It tells you how many bytes have actually been read. And until it's not -1, you should continue to read, in a loop.

Read the Java tutorial on byte streams.

That said, you're making things difficult. Why don't you write the object directly to the socket output stream, and read the object directly from the socket input stream at the other side?