需要帮助改进java客户端端口侦听器

我有一小段代码在包含SWING控件的applet中运行,用于将信息写入某个端口上的套接字,然后侦听响应。 这工作正常,但它有一个问题。 端口侦听器基本上处于循环中,直到服务器收到null。 我希望用户能够在等待服务器响应的同时在applet实例化的GUI中执行其他操作(这可能需要几分钟才能完成)。 我还需要担心服务器和客户端之间的连接断开连接。 但是编写代码的方式,applet似乎会冻结(它实际上处于循环中),直到服务器响应。 如何允许侦听器在后台进行侦听,允许程序中发生其他事情。 我假设我需要使用线程,我确信这个应用程序,它很容易实现,但我缺乏坚实的线程基础阻碍了我。 下面是代码(你可以看到它是多么简单)。 如何改进它以使其做我需要做的事情>

public String writePacket(String packet) { /* This method writes the packet to the port - established earlier */ System.out.println("writing out this packet->"+packet+"<-"); out.println(packet); String thePacket = readPacket(); //where the port listener is invoked. return thePacket; } 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) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } 

谢谢,

埃利奥特

有很多不同的方法可以在不同的线程上执行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() { @Override protected String doInBackground() throws Exception { // called on a background thread /* This method writes the packet to the port - established earlier */ 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; } } 

所有网络I / O都应该在一个单独的线程中。

BTW readLine()在服务器关闭连接时返回null,而不是在它刚刚完成数据发送时返回。