Java 使用InputStream通过TCP套接字接收多个图像
每次我从相机拍摄图像时,我都会尝试将多张图像一张一张地从我的android手机自动发送到服务器(PC) 问题是Java 使用InputStream通过TCP套接字接收多个图像,java,sockets,tcp,inputstream,Java,Sockets,Tcp,Inputstream,每次我从相机拍摄图像时,我都会尝试将多张图像一张一张地从我的android手机自动发送到服务器(PC) 问题是read()函数只会第一次阻塞。因此,从技术上讲,只有一幅图像被完美地接收和显示。但是在这之后,当is.read()返回-1时,此函数不会阻塞,并且无法接收多个图像 对于服务器来说,代码很简单 while (true) { InputStream is = null; FileOutputStream fos = null; BufferedOutputStrea
read()
函数只会第一次阻塞。因此,从技术上讲,只有一幅图像被完美地接收和显示。但是在这之后,当is.read()
返回-1
时,此函数不会阻塞,并且无法接收多个图像
对于服务器来说,代码很简单
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();
}
}
非常感谢您的帮助。如果您希望通过同一个流接收多个图像,您应该建立某种协议,例如:读取表示每个图像字节数的int
<int><b1><b2><b3>...<bn> <int><b1><b2><b3>...<bn> ...
。。。
然后,您可以通过以下方式读取每个图像:
...
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();
}
。。。
is=sock.getInputStream();
BufferedInputStream bis=新的BufferedInputStream(is);
如果(is!=null)
System.out.println(“不为空”);
while(true){
//读取前4个字节,int表示下图的长度
int imageLength=(bis.read()
...
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();
}