Reputation: 3168
I'm new to Java Socket Programming and currently exploring its Socket APIs. I've created a new simple App that starts ServerSocket
and listens for Clients, when client writes something on the socket, server allocates new thread for that client. I tried first using console app and everything worked fine. Now, I've made GUI for the same using SWT (WindowBuilder plugin in Eclipse 3.7). The Window has a button which toggles listening of the server On and Off. Below is the code written in SWT Button's click event which will start listening for clients.
if(!isServerRunning)
{
btnServerRunner.setText("Stop Server");
isServerRunning = true;
while (listening)
{
try
{
new ClientHandler(listener.accept()).start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
else
{
try
{
listener.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
btnServerRunner.setText("Start Server");
isServerRunning = false;
}
The ClientHandler
class has Thread
extended and hence will launch new thread for every new client. I know above code works for console app but will not work for GUI since I'm throwing app into infinite loop of listening for client sockets in button's click. What is the elegant way to start and stop ServerSocket
for listening for clients that doesn't freeze the app UI?
Thanks.
Upvotes: 0
Views: 712
Reputation: 16364
You should use a separate thread for accepting client connections. The button could just start and interrupt that thread.
Upvotes: 2
Reputation: 80603
You need to run your Server in a separate thread (from the UI dispatch thread).
Upvotes: 1