Java Stop Server Thread
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()开发者_Python百科;
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.
Close the server socket from an external thread. As per the documentation on Serversocket.close() the blocking accept will throw a SocketException and you can shutdown your thread.
After initializing your ServerSocket, use setSoTimeout. Put the accept in a loop, catching the timeouts. Break from the loop and return from run
based on whether you want to continue or not.
精彩评论