Reputation: 123
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
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:
socket.accept()
OutputStream
using the new connection.OutputStream
with an ObjectOutputStream
.ObjectOutputStream
(i.e. write some serializable data into it and flush).Upvotes: 3