问题描述
我每次从相机中捕捉图像时,我都会尝试从我的Android手机中自动发送多个图像到服务器(PC)。
I am trying to send multiple images one by one automatically from my android phone to the Server (PC) each time I capture an image from the camera.
问题是 read()
函数仅在第一次阻塞。因此,从技术上讲,只接收并完美显示一个图像。但之后当 is.read()
返回 -1
时,此函数不会阻止,并且多个图像无法接收。
The problem is the read()
function only blocks the first time. So, technically only one image is received and shown perfectly. But after that when is.read()
returns -1
, this function does not block and multiple images could not receive.
代码对于服务器来说很简单
The code is simple for the Server
while (true) {
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
is = sock.getInputStream();
if (is != null)
System.out.println("is not null");
int bufferSize = sock.getReceiveBufferSize();
byte[] bytes = new byte[bufferSize];
while ((count = is.read(bytes)) > 0)
{
if (filewritecheck == true)
{
fos = new FileOutputStream("D:\\fypimages\\image" + imgNum + ".jpeg");
bos = new BufferedOutputStream(fos);
imgNum++;
filewritecheck = false;
}
bos.write(bytes, 0, count);
System.out.println("count: " + count);
}
if (count <= 0 && bos != null) {
filewritecheck = true;
bos.flush();
bos.close();
fos.close();
}
}
收到图像后的输出是
is not null
is not null
is not null
is not null
is not null
is not null
is not null
is not null
...
...
...
...
任何帮助都将受到高度赞赏。
Any help will be highly appreciated.
推荐答案
如果你想在同一个流上接收多个图像,你应该建立某种协议,例如:读取一个表示每个图像的字节数的int。
If you want to receive multiple images over the same stream you should establish some kind of protocol, example: read an int that represent the number of bytes of each image.
<int><b1><b2><b3>...<bn> <int><b1><b2><b3>...<bn> ...
然后你可以这样读取每张图片:
Then you can read each image this way:
...
is = sock.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
if (is != null)
System.out.println("is not null");
while (true) {
// Read first 4 bytes, int representing the lenght of the following image
int imageLength = (bis.read() << 24) + (bis.read() << 16) + (bis.read() << 8) + bis.read();
// Create the file output
fos = new FileOutputStream("D:\\fypimages\\image" + imgNum + ".jpeg");
bos = new BufferedOutputStream(fos);
imgNum++;
// Read the image itself
int count = 0;
while (count < imageLength) {
bos.write(bis.read());
count += 1;
}
bos.close();
}
请注意,您还必须修改发件人,并将imageLength放入与你收到的字节顺序相同。
Note that you also have to modify the sender, and put the imageLength in the same byte order than you are receving it.
另请注意,一次读取和写入一个字节不是最有效的方法,但它更容易和缓冲流照顾大部分性能影响。
Also note that reading and writting one byte at a time isn't the most efficient way, but it's easier and the buffered streams take care of most of the performance impact.
这篇关于使用InputStream通过TCP套接字接收多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!