Java 从套接字接收多字节数组
我目前正在开发一个远程桌面应用程序。服务器部分在Android设备上运行,客户端部分在PC/Raspberry PI上运行。我在从Android接收位图截图时遇到了一个问题,以字节数组的形式发送。 Android服务器代码如下所示:Java 从套接字接收多字节数组,java,android,arrays,sockets,bitmap,Java,Android,Arrays,Sockets,Bitmap,我目前正在开发一个远程桌面应用程序。服务器部分在Android设备上运行,客户端部分在PC/Raspberry PI上运行。我在从Android接收位图截图时遇到了一个问题,以字节数组的形式发送。 Android服务器代码如下所示: //os = new ObjectOutputStream(s.getOutputStream()); public void run() { while(true){ try {
//os = new ObjectOutputStream(s.getOutputStream());
public void run() {
while(true){
try {
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
int quality = 100;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
byte[] byteArray = stream.toByteArray();
if(byteArray.length>0) {
os.writeInt(byteArray.length);
os.write(byteArray, 0, byteArray.length);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}}}
PC上的接收器应用程序如下所示:
//ois = new ObjectInputStream(s.getInputStream());
public void run() {
while(true){
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int size = ois.readInt();
System.out.println(size);
byte[] data = new byte[size];
int length = 0;
while ((length = ois.read(data,0,size)) != -1) {
out.write(data, 0, size);
out.flush();
}
byte[] bytePicture = out.toByteArray();
out.close();
BufferedImage buffImage = byteArrayToImage(bytePicture);
ImageIcon imgIcon = new ImageIcon(buffImage);
l.setIcon(imgIcon);
} catch (IOException e) {
}}}
byteArrayToImage
问题是,在receiver应用程序中,我得到Java OutOfMemoryException,因为我无法区分传入的屏幕截图。我真的不知道如何准确地读取位图的大小作为字节数组,然后显示它并读取另一个和另一个。任何帮助都将不胜感激。提前感谢。在阅读时,您必须准确读取大小字节,您没有这样做,因此可以跨越消息边界,顺便说一句,您可以使用谷歌的协议缓冲区,使您的生活更轻松“out.writedata,0,size;”。应该是out.writedata,0,length;。您应该添加一个变量int nreceived=0;在循环中添加长度。不要求读取大小字节,但要求读取未接收的大小字节。检查nreceived是否等于大小。@greenapps非常感谢:
public static BufferedImage byteArrayToImage(byte[] bytes) {
BufferedImage bufferedImage = null;
try {
InputStream inputStream = new ByteArrayInputStream(bytes);
bufferedImage = ImageIO.read(inputStream);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return bufferedImage;
}