Dante
Dante

Reputation: 123

Java getting ObjectInputStream ObjectOutputStream from a socket

I have an application that is based on server- multiple clients interaction.This is the thread that i use in the server class to create a new thread where i accept all the new sockets:

    Thread acceptingThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    Socket s = serverSocket.accept();
                    listaSocket.add(s);
                    listaOis.add(new ObjectInputStream(s.getInputStream()));
                    listaOos.add(new ObjectOutputStream(s.getOutputStream()));
                    System.out.println("Client connected");
                } catch (IOException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

    });
    acceptingThread.start();




private ServerSocket serverSocket;
private ArrayList<Socket> listaSocket;
private ArrayList<ObjectInputStream> listaOis;
private ArrayList<ObjectOutputStream> listaOos;

The lines that block the programs are :

                    listaOis.add(new ObjectInputStream(s.getInputStream()));
                    listaOos.add(new ObjectOutputStream(s.getOutputStream()));

Upvotes: 0

Views: 1976

Answers (1)

Carlos Miranda
Carlos Miranda

Reputation: 381

Your code is blocking in this particular line:

                    listaOis.add(new ObjectInputStream(s.getInputStream()));

Take note of the behavior of this ObjectInputStream constructor. From the Javadoc:

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

Getting the InputStream from the incoming connection means that serialized data needs to be sent through the connection. This means that you have to do the following before the constructor will proceed:

  1. Connect from the client side. I presume you are already doing this since you can get through socket.accept()
  2. Open an OutputStream using the new connection.
  3. Wrap the OutputStream with an ObjectOutputStream.
  4. Send some data through the ObjectOutputStream (i.e. write some serializable data into it and flush).

Upvotes: 3

Related Questions