Search code examples
javasocketsserversocket

Server Socket - Sending a test message to detect connection


I'm trying to use server sockets to set up a connection between a client and a server. I'm also not using java.nio.

The problem is that I'm constantly sending a test message, and detecting whether if it is successful in sending the message (the client is still connected), if not, then the client is disconnected.

Shown here:

    try
    {
        Scanner in = new Scanner(socket.getInputStream());
        BufferedReader in_2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        while(stopThread)
        {
                if(in_2.ready())
                {
                    String message = in_2.readLine();
                    dt = new DateTime();

                    PrintStream out = new PrintStream(socket.getOutputStream());
                    server.detect(message, dataSets, out);

                    dataSets.add(message);
                    GUI.textArea_1.append(message + "\r\n");
                    GUI.textArea_1.setCaretPosition(GUI.textArea_1.getDocument().getLength());
                }
                else
                {
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    out.println("Testing Connection \r\n");
                    if(out.checkError())
                    {
                        try
                        {
                            socket.close();
                        } 
                        catch (IOException e) 
                        {
                            e.printStackTrace();
                        }
                        stopThread = false;
                        GUI.textArea.append(userName + " disconnected \r\n");
                        GUI.textArea.setCaretPosition(GUI.textArea.getDocument().getLength());
                        server.inputDataForm(userName, dt, dataSets);
                    }
                    Thread.sleep(3000);
                }

        }

The problem is that the Thread.sleep(3000) is actually interfering with getting data, since after 3 seconds, I will get a huge amount of data (because I stopped the thread for 3 seconds).

Now, what I proposed is a anonymous class in the else statement.

class runThread implements runnable
{
     void run()
     {
          //Put the else statement here
     }
}

But the stopThread = false is not a constant, which I'm trying to control.

Other threads I've searched only puts variables inside main inside the anonymous class, but I need stopThread to stop the while loop if the client is disconnected.

Does anyone have an idea?

Thanks!


Solution

  • Why don't you make a class that implements runnable but also has the method stop();

    public class MyRunner implements Runnable(){
        MutableBoolean stop = false;
        public void run(){...}
        public void stop(){
            stop = true;
        }
    }