Java Stop Server Thread

Posted by ikurtz on Stack Overflow See other posts from Stack Overflow or by ikurtz
Published on 2010-05-10T17:17:33Z Indexed on 2010/05/10 17:24 UTC
Read the original article Hit count: 380

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about server