我正在尝试将图像从“服务器”(其目的是发送图像)发送到作为 Android 设备的“客户端”。之间的套接字保持打开状态,图像不断出现。问题是:
- 我不知道图像的大小(它可以改变);
- 图像不是 BMP 格式。
在我下面的代码中:
- 客户端在图像传输后不会停止读取(
-1
读取时我没有得到),它会在套接字关闭时停止; - 完成读取后,输入流不会被清除,并且会一遍又一遍地读取相同的图像。
起初,我尝试发送 2 个我知道大小的 BMP 图像(两者大小相同)。这是服务器代码:
public static void main(String[] args) {
try {
ServerSocket s = new ServerSocket(4488);
System.out.println("Waiting for a connection . . . . ");
Socket socket = s.accept();
System.out.println("Connected!");
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
Thread.sleep(2000);
File myImageFile = new File("c:\\1\\a.bmp");
FileInputStream fis = new FileInputStream(myImageFile);
byte[] data = new byte[(int) myImageFile.length()];
byte[] tmp = new byte[0];
byte[] myArrayImage = new byte[0];
int len = 0 ;
int total = 0;
while( (len = fis.read(data)) != -1 ) {
total += len;
tmp = myArrayImage;
myArrayImage = new byte[total];
System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
System.arraycopy(data,0,myArrayImage,tmp.length,len);
}
//
fis.close();
dataOutputStream.write(myArrayImage);
dataOutputStream.flush();
Thread.sleep(2000);
myImageFile = new File("c:\\1\\b.bmp");
fis = new FileInputStream(myImageFile);
data = new byte[(int) myImageFile.length()];
tmp = new byte[0];
myArrayImage = new byte[0];
len = 0 ;
total = 0;
while( (len = fis.read(data)) != -1 ) {
total += len;
tmp = myArrayImage;
myArrayImage = new byte[total];
System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
System.arraycopy(data,0,myArrayImage,tmp.length,len);
}
fis.close();
dataOutputStream.write(myArrayImage);
dataOutputStream.flush();
Thread.sleep(2000);
socket.close();
s.close();
这是客户端代码:
@Override
public void run() {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] byteChunk = null;
int c;
if (_dataInputStream != null) {
while (true) {
try {
Thread.sleep(200);
} catch (Exception e) {
}
try {
byteChunk = new byte[1024];
while ((c = _dataInputStream.read(byteChunk)) != -1){
buffer.write(byteChunk, 0, byteChunk.length);
}
} catch (IOException e) {
e.printStackTrace();
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(buffer.toByteArray(), 0, buffer.size());
if (bitmap != null) {
_handler.post(new Runnable() {
public void run() {
_iv.setImageBitmap(bitmap);
_iv.invalidate();
}
});
}
buffer.reset();
}
}
}
现在,正如我所说,客户端一直停留在 while 循环上,直到套接字关闭,然后(无论我发送多少图像,因为我在客户端创建了一个仅适合 1 个图像的字节数组)它一直在读取这个一直都是第一张图。
任何想法我做错了什么?
Ps 如果图像不是 BMP,我在客户端代码中编写的解码会起作用吗?我要发送的真实图像是PNG。