需要帮助来改善Java客户端端口侦听器

需要帮助来改善Java客户端端口侦听器,第1张

需要帮助来改善Java客户端端口侦听器

有很多不同的方法可以使IO在不同的线程上执行,但是在这种情况下,您可能要使用SwingWorker。

您的代码如下所示:

private final Executor executor = Executors.newSingleThreadExecutor();public void writePacket(final String packet) {  // schedules execution on the single thread of the executor (so only one background operation can happen at once)  //  executor.execute(new SwingWorker<String, Void>()      {        @Override        protected String doInBackground() throws Exception        {          // called on a background thread                    System.out.println("writing out this packet->"+packet+"<-");          System.out.println(packet);          String thePacket = readPacket();  //where the port listener is invoked. return thePacket;         }        @Override        protected void done()        {          // called on the Swing event dispatch thread          try          { final String thePacket = get(); // update GUI with 'thePacket'          }          catch (final InterruptedException e)          { // TODO Auto-generated catch block e.printStackTrace();          }          catch (final ExecutionException e)          { // TODO Auto-generated catch block e.printStackTrace();          }         }      });}private String readPacket() {  String thePacket ="";  String fromServer="";  //Below is the loop that freezes everything.     try   {    while ((fromServer = in.readLine()) != null)     {       if (thePacket.equals(""))         thePacket = fromServer;      else         thePacket = thePacket+newline+fromServer;    }    return thePacket;  //when this happens, all listening should stop.     }   catch (IOException e)   {    e.printStackTrace();    return null;  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5498736.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存