5

I'm making a client-server application, in which the user can turn on or switch off the server from a gui; in order to let it work, I use a SwingWorker nested class. All seems to work correctly, but when I switch off the server and re-turn it on it doesn't work, probably because there is still another instance open of it that can't be overwritten: server is blocked on the accept() method. I want to kill the previous instance when the user presses the switch off button, but I don't know how.

Here's the SwingWorker class that gives me problems:

class SwingWorkGUI extends SwingWorker
    {
        @Override
        protected Integer doInBackground() throws Exception {
            int delay = 1000; 
            final Timer time = new Timer(delay, null);
            time.addActionListener( new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (Server.up == true){
                        upTimeMillis += 1000;
                        long diff = upTimeMillis/1000;
                        long numHrs = diff/60;
                        diff = diff%60;
                        long numMins = diff/60;
                        long numSecs = diff%60;
                        upTime.setText(numHrs + ":" + numMins + ":" + numSecs);
                    }
                    else {
                        upTime.setText("Server Actually Down");
                        time.stop();
                    }
                }           
            });
            time.start();
            mainServer = new Server();
            return null;
        }
    }

Everytime the Turn On button is pressed, the actionPerformed determines whether the server is already on or not, then if not runs

SwingWorkGUI swg = new SwingWorkGUI(); 
swg.execute();

The execution blocks in the following instruction, but only the second (third,ecc.) time it is called:

mainServer = new Server();

Server.up is a static variable that helps me to kill the while(true) method in server.

How can I kill the open instance without closing all the application?

4

1 回答 1

0

如果我理解正确,您的问题是ServerSocket对象在accept()通话中被阻止,您需要取消阻止它。一些选项:

  1. 从另一个线程调用ss.close()(假设ss是你的ServerSocket对象)。这将使accept()抛出一个SocketException. 参考:Javadocs forServerSocket.close()

  2. 从另一个线程创建一个新Socket线程并连接到您自己的服务器。这将取消阻止accept()呼叫。现在你可以检查你的Server.up标志了。

  3. 在您的 上设置超时ServerSocket,例如 5 秒。这将使accept()throwInterruptedIOException超时。参考:Javadocs forSO_TIMEOUT

于 2013-05-28T11:47:11.820 回答