I have a problem with using a ServerSocket
in my application.
I'm creating the ServerSocket
in the constructor of my application. The constructor of the socket calls the accept()
method to wait for a client to connect.
The problem is that the accept()
method is freezing my whole application until a client connects. So I would like to ask if there's an alternative to creating the whole ServerSocket
in a separate thread, that the constructor of the ServerSocket
and its accept()
method is called beside my main application?
Edit:
Thanks to Olivier for the advice, putting the .accept into a runnable and creating a threadpool to handle the clientconnections.
Thats my code right now:
public void start(){
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
objectout = new ObjectOutputStream(clientSocket.getOutputStream());
clientProcessingPool.submit(new ClientTask(clientSocket,objectout));
}
} catch (IOException e) {
System.err.println("Accept failed.");
}
}
};
Everythings running fine! Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…