gpt4 book ai didi

java - 需要帮助改进 Java 客户端端口监听器

转载 作者:行者123 更新时间:2023-11-30 09:46:05 25 4
gpt4 key购买 nike

我有一小段代码在包含 SWING 控件的小程序中运行,用于将信息写入特定端口上的套接字,然后监听响应。这工作正常,但有一个问题。端口监听器本质上处于循环中,直到服务器接收到 null。我希望用户在等待服务器响应时能够在 applet 实例化的 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;
}

}

谢谢,

埃利奥特

最佳答案

有很多不同的方法可以让 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


/* 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;
}
}

关于java - 需要帮助改进 Java 客户端端口监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7328033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com