'one single ObjectOutputStream for multiple use with sockets

I'm trying to make a very basic example of a network connection where I use an ObjectOutputStream, ObjectInputStream and sockets. The client sends the string "Hello" to the server. As you see this string is sent 10 times with the very same ObjectOutputStream. Then the server sends the string "Goodbye" to the client. The console should display 10 times the string "hello" and 10 times the string "Goodbye". But they are shown only one time. I read in many threads about the method reset() of the ObjectOutputStream. But it does not seem to work for me. Any ideas what the problem is? I've already tried many different things without success.

Here is the client:


    try  
    {       
        Socket socket = new Socket("localhost", 5555);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        int i = 10;
        while (i > 0) 
        {           
            //send String
            out.writeObject("Hello");               
            out.flush();
            out.reset();

            //receive String
            String result = (String) in.readObject();
            System.out.println(result);
            i--;
        }       
    } catch (IOException e) 
    {
        e.printStackTrace();
    } catch (ClassNotFoundException e) 
    {           
        e.printStackTrace();
    } finally
    {
        out.close();
        in.close();
        socket.close();
    }

Here is the server:


try
    {   
        ServerSocket server = new ServerSocket(5555);
        while(true)
        {
            try
            {
                Socket client = server.accept();                            
                ObjectInputStream in = new ObjectInputStream(client.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());

                //receive String
                String input = (String) in.readObject();
                System.out.println(input);

                out.writeObject("Goodbye");
                out.flush();
                out.reset();

            } catch(IOException e1)
            {
                e1.printStackTrace();
            } catch (ClassNotFoundException e) 
            {               
                e.printStackTrace();
            }
        }
    } catch(IOException e2)
    {
        e2.printStackTrace();
    }


Solution 1:[1]

Your server is only reading and writing once to each accepted socket. So the client can't possibly read an object ten times.

Your server also isn't closing the stream when it's finished.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user207421