Kim Ericko
Kim Ericko

Reputation: 21

Java: Send and recive an Object over Socket

I am a student and learning Network Programming and have a some problem.

This is my client:

public class Test2Client_Tranfer_An_Obj {

Socket socket = null;
ObjectOutputStream out;
ObjectInputStream in;

public Test2Client_Tranfer_An_Obj() {
    try {
        socket = new Socket("localhost", 12345);

        out = new ObjectOutputStream(socket.getOutputStream());
        in = new ObjectInputStream(socket.getInputStream());
        System.out.println("Ready");

        System.out.println("" + in.readUTF());
        System.out.println("" + in.readUTF());
        System.out.println("Recived");

        out.writeUTF("hihi");

        System.out.println("Sended");




    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {

    System.out.println("Client");
    Test2Client_Tranfer_An_Obj test = new Test2Client_Tranfer_An_Obj();
}

}

This my Server:

public class Test2Server_Tranfer_An_Obj {

ServerSocket serverSocket;
ObjectOutputStream out;
ObjectInputStream in;

public Test2Server_Tranfer_An_Obj() {

    try {
        serverSocket = new ServerSocket(12345);
        Socket socket = serverSocket.accept();

        out = new ObjectOutputStream(socket.getOutputStream());
        in = new ObjectInputStream(socket.getInputStream());
        System.out.println("Ready!");
        out.writeUTF("huhu");
        out.writeUTF("hoho");
        System.out.println("Sended");

        String s = in.readUTF();
        System.out.println("" + s);
        System.out.println("Recived");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    System.out.println("Server");
    Test2Server_Tranfer_An_Obj demo = new Test2Server_Tranfer_An_Obj();

}

}

But, when i run my program, this result:

Server Console

Server Ready! Sended

Client Console

Client Ready

Anybody can tell me why and what i can do? Thank for reading! Hope recive you answer

Upvotes: 1

Views: 808

Answers (2)

Ricardo Machado
Ricardo Machado

Reputation: 782

In your server after write to the outputstream. you have to add out.flush() to write to socket

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533820

Object Stream is overkill in this case. You are not actually using writeObject/readObject and using DataInputStream and DataOutputStream would do what you want.

In this particular case, an Object Stream is buffered, which means that small writes are buffered until you either flush() or close() the stream to improve performance. As you don't do either, the writeUTF only writes to memory, not the Socket.

c.f. Data Streams are not buffered by default.

Upvotes: 1

Related Questions