【发布时间】:2011-09-07 01:46:14
【问题描述】:
我有一小段代码在一个包含 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;
}
}
谢谢,
艾略特
【问题讨论】:
-
Java 并发实践是加强线程基础的好读物;除了你是对的;用于套接字连接的线程池。
标签: java multithreading sockets