Server based SwingWorker does not Stop

◇◆丶佛笑我妖孽 提交于 2019-12-18 07:14:47

问题


I have a boolean variable to control the execution of the server (start/stop) :

private boolean ecoute=true;

here is my class:

 sw=new SwingWorker<String,Void> (){

 protected String doInBackground() throws Exception {
    try {

            server = new ServerSocket(Integer.parseInt(port.getText()));

            String str1="waiting for connexion..";
            String str2="Connexion ok";

            log.append(str1+"\n");
            PrintWriter out=null;
            BufferedReader in=null;
            Socket socClient=null;
         while(ecoute){

                socClient = server.accept();  
                    log.append(str2+"\n");
                     in = new BufferedReader(
                                    new InputStreamReader(socClient.getInputStream())
                                   );
                   out = new PrintWriter(
                     new BufferedWriter(
                        new OutputStreamWriter(socClient.getOutputStream())), 
                     true);
                    String str = in.readLine();
                    log.append(str+"\n");

         }

            in.close();
            out.close();
            socClient.close();
            return "***End Reception***";
    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        return "***Error Reception***";
    }

       }

       protected void done(){
       String m="";
            try {
                m=get();
            } catch (InterruptedException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        log.append(m+"\n");

       }
    };
   sw.execute();
  }

when I click the button to pass the variable to false for my thread get out of the infinite loop,nothing happens :

 private void arretReceptionActionPerformed(java.awt.event.ActionEvent evt) {


    ecoute=false;

}

I replaced ecoute=false; by sw.calcel(true); also nothing new ...

any suggestion ?


回答1:


Your ServerSocket is what's causing the loop to not terminate. Even though 'ecoute' is false, server.accept() will block until one of the following two conditions is met:

  1. A connection is made to the ServerSocket
  2. The ServerSocket is closed.

You need to do one of these two things so that the call to server.accept() will stop blocking. Mind you - if you choose to close the ServerSocket, an IOException will get thrown. It would probably be better to wrap the call to server.accept() in the try block, instead of wrapping the entire doInBackground() function.



来源:https://stackoverflow.com/questions/9588543/server-based-swingworker-does-not-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!