需要帮助来改善Java客户端端口侦听器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了需要帮助来改善Java客户端端口侦听器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2784字,纯文字阅读大概需要4分钟。
内容图文
![需要帮助来改善Java客户端端口侦听器](/upload/InfoBanner/zyjiaocheng/692/165bfb251c4f4e84b648c2a8eec905f4.jpg)
我有一小段代码在包含SWING控件的applet中运行,用于将信息写入特定端口上的套接字,然后侦听响应.这可以正常工作,但是有问题.端口侦听器实际上处于循环状态,直到服务器接收到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客户端端口侦听器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。