Java Stop Server Thread
- by ikurtz
the following code is server code in my app:
private int serverPort;
private Thread serverThread = null;
public void networkListen(int port){
serverPort = port;
if (serverThread == null){
Runnable serverRunnable = new ServerRunnable();
serverThread = new Thread(serverRunnable);
serverThread.start();
} else {
}
}
public class ServerRunnable implements Runnable {
public void run(){
try {
//networkConnected = false;
//netMessage = "Listening for Connection";
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
ServerSocket serverSocket = new ServerSocket(serverPort, backlog);
commSocket = serverSocket.accept();
serverSocket.close();
serverSocket = null;
//networkConnected = true;
//netMessage = "Connected: " + commSocket.getInetAddress().getHostAddress() + ":" +
//commSocket.getPort();
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
} catch (IOException e){
//networkConnected = false;
//netMessage = "ServerRunnable Network Unavailable";
//System.out.println(e.getMessage());
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
}
}
}
The code sort of works i.e. if im attempting a straight connection both ends communicate and update.
The issue is while im listening for a connection if i want to quit listening then the server thread continues running and causes problems.
i know i should not use .stop() on a thread so i was wondering what the solution would look like with this in mind?
EDIT: commented out unneeded code.