【问题标题】:android tcp client file receiveandroid tcp客户端文件接收
【发布时间】:2012-09-11 20:07:44
【问题描述】:

我正在尝试通过套接字从 python 服务器向 android 客户端发送文件(具体为 png)。我知道我的 python 服务器正在发送数据,我只是不知道如何在 android 端接收数据。这是接收文件的代码。

    String path = Environment.getExternalStorageDirectory().toString() +"/tmp/test.png";     
        try {
            socket = new Socket("192.168.1.129", 29877);

             is = socket.getInputStream();
             out = new FileOutputStream(path);
            byte[] temp = new byte[1024];
            for(int c = is.read(temp,0,1024); c > 0; c = is.read(temp,0,1024)){
                out.write(temp,0,c);
                Log.d("debug tag", out.toString());
            }
            Log.d("debug tag", temp.toString());

            Bitmap myBitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            imageView.setImageBitmap(myBitmap);

感谢您的建议。

【问题讨论】:

    标签: java android sockets


    【解决方案1】:

    您正在从套接字读取 1K 块并将它们保存到文件中。然后您尝试将最后一个块解释为位图。这不起作用。

    要么在保存后从文件中读取图像,要么将其全部缓存在内存中。

    【讨论】:

    • 我如何将它全部缓冲到内存中?例如?
    • 你可以使用类似java.io.ByteArrayOutputStream docs.oracle.com/javase/6/docs/api/java/io/…
    • 哇老兄,谢谢,我不敢相信我没有意识到我只是想读最后一块……愚蠢……非常感谢。
    猜你喜欢
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2020-10-02
    • 2012-03-15
    相关资源
    最近更新 更多