2016-12-30 76 views
-2

对不起,我的游泳池英语。 我有一个javaFx应用程序需要连接到许多套接字服务器(超过40),这是在Android手机开始。 当连接到服务器时,我建立一个线程来保存长连接,每隔600毫秒服务器将SCREENSHOT(二进制)发送到我的应用程序。 javaFx应用程序不能是服务器。 下面是部分代码:如何在Socket长连接中保持CPU使用率较低

while (ScreenMonitorService.isConnectionAll()){ 
Future<Image> f = ThreadPoolUtil.getThreadPool().submit(new Callable<Image>() { 
    @Override 
    public Image call() throws Exception { 
     return readImage(inputStream, outputStream); 
    } 
    }); 
Image fxImage = f.get(); 
Platform.runLater(()->{ 
    device.getImageView().setImage(fxImage); 
}); 


//what readImage do 
private synchronized Image readImage(InputStream inputStream, OutputStream outputStream) throws IOException { 
try { 
     Thread.sleep(700);<==== This is the now solution for high cpu performtion , but it doesn't work 
    } catch (InterruptedException e) { 
     logger.error("=====> error", e); 
    } 
    int fileLen = readInt(inputStream); 
    int readLength = fileLen; 
    int tempLength = 0; 
    int n; 
    byte[] bt = new byte[readLength]; 
    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
    while ((n = inputStream.read(bt,0,readLength)) > 0) { 
     tempLength += n; 
     readLength = tempLength + n > fileLen ? fileLen - tempLength : readLength; 
     bout.write(bt,0,n); 
    } 
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); 
    BufferedImage image = ImageIO.read(bin); 
    Image fxImage = SwingFXUtils.toFXImage(image,null); 
    writeInt(outputStream,1); 
    return fxImage; 
} 

我知道这是繁忙的,瓦亭,这使得坏CPU的性能。 我已经使用nio | notify/wait | blockqueue尝试解决问题,但失败。 可能有人可以给我一些建议来解决这个问题,谢谢。

回答

0

实际上......你并不是在等待,而sleep也不是你问题的原因。

你真正应该做的是个人资料查看它在哪里花费大部分时间的代码。我嫌疑,它实际上是在这两个电话:

BufferedImage image = ImageIO.read(bin); 
    Image fxImage = SwingFXUtils.toFXImage(image, null); 

换句话说,我怀疑,大多数CPU的在转换图像是怎么回事。如果是这种情况,那么你需要找出一种办法来减少图像处理。

这也可能是一个与GC相关的问题,但分析也会为此提供证据。


我注意到你在处理它之前缓冲了整个文件。这可能会让事情变得更慢。你可以通过将InputStream包装在BufferedInputStream中并将BIS传递给ImageIO.read来避免这种情况。但我不认为字节的双重处理是主要问题。

+0

我已经剖析了代码。 – alongsea2

+0

转换成本约为200毫秒。 – alongsea2

+0

也感谢您的建议 – alongsea2