我有一个布尔变量来控制服务器的执行(启动/停止):
private boolean ecoute = true;
这是我的课:
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(); }
当我单击按钮将变量传递给false时,我的线程退出无限循环,什么也没发生:
private void arretReceptionActionPerformed(java.awt.event.ActionEvent evt) { ecoute=false; }
我也换ecoute=false;了 sw.calcel(true);新东西…
ecoute=false;
sw.calcel(true);
有什么建议吗?
您的ServerSocket是导致循环不终止的原因。即使’ecoute’为假,server.accept()也会阻塞,直到满足以下两个条件之一:
您需要执行以下两项操作之一,以便对server.accept()的调用将停止阻塞。提醒您- 如果您选择关闭ServerSocket,则会抛出IOException。最好将对server.accept()的调用包装在try块中,而不是包装整个doInBackground()函数。