繁体   English   中英

将图像从 java 服务器发送到 android 应用程序

[英]sending image from java server to android app

我想使用以下代码将图像文件从 java 服务器发送到 android 应用程序:

服务器(Java):

File file = new File("./clique.jpg");

FileInputStream stream = new FileInputStream(file);

DataOutputStream writer = new DataOutputStream(socket.getOutputStream());        

byte[] contextB = new byte[4096];

int n;
int i = 0;
while ( (n=stream.read(contextB))!=-1 ){
    writer.write(contextB, 0, n);
    writer.flush();
    System.out.println(n);
    i+=n;
}
writer.flush();
stream.close();

android 应用程序:

DataInputStream reader = new DataInputStream(socket.getInputStream());
            byte[] buffer = new byte[4096];
            ByteArrayOutputStream content = new ByteArrayOutputStream();

            int n;
            int i = 0;
            reader = new DataInputStream(socket.getInputStream());
            while ( (n=reader.read(buffer)) != null){                
                content.write(buffer, 0, n);
                content.flush();

            }

            Utility.CreateImageFile(content.toByteArray());

我注意到的是,在 android 应用程序 n 中,当我从 4096 大小的服务器字节块发送时,读取字节数不是 4096,我也无法得到 n=-1,这是 stream 的结尾,它阻塞直到我关闭应用程序然后我得到 n = -1。

关于您一次读取的字节数与您写入的字节数无关 - 它在很大程度上取决于网络条件,并且会随着每个块而变化(基本上与在短时间内设法传输的字节数一样多)读取之间的时间与您将在读取块中获得的时间一样多。

Regarding the end of stream - in your server code you have forgotten to close the output stream (you only close the stream which is input stream - you should also close the writer which in turn will close the underlying output stream.

两条评论:

1)我真的建议使用缓冲的读取器/写入器来包装写入/读取器 - 您将获得的代码会更好,您不必自己创建/管理缓冲区。

2) 使用 try {} finally 并在 finally 子句中关闭您的流 - 这是确保您将关闭流并释放资源的最佳实践,即使在读/写时出现问题也是如此。

您的 android 代码有问题:

while ( (n=reader.read(buffer)) != null) {

n 不能为 null。

在服务器上循环之后使用 writer.close() 而不是 writer.flush()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM