我有一小段代码在包含 SWING 控件的小程序中运行,用于将信息写入某个端口上的套接字,然后侦听响应。这工作得很好,但是有一个问题。端口侦听器本质上处于循环状态,直到服务器接收到 null。我希望用户在等待服务器响应时能够在小程序实例化的 GUI 中执行其他操作(这可能需要几分钟的时间)。我还需要担心服务器和客户端之间的连接断开。但按照代码的编写方式,小程序似乎会冻结(实际上是在循环中),直到服务器响应为止。我如何允许侦听器在后台进行侦听,从而允许程序中发生其他事情。我假设我需要使用线程,并且我确信对于这个应用程序来说,它很容易实现,但我缺乏坚实的线程基础阻碍了我。下面是代码(您可以看到它是多么简单)。我怎样才能改进它,让它做我需要它做的事情>
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;
}
}
Thanks,
Elliott
有很多不同的方法可以在不同的线程上执行 IO,但在这种情况下您可能想要使用摇摆工人 http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html.
你的代码看起来像这样:
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
/* 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)