两个android用tcp传递图片

两台android设备发送文件。

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

out.writeInt(bytes.length);

发送的时候需要发送文件的大小。否则会报错。java.lang.NegativeArraySizeException

发送端:

byte [] imageByte;  
FileInputStream inputStream ;
File file = new File(Environment.getExternalStorageDirectory() + "/" + "fff.jpg");
        try {
            inputStream = new FileInputStream(file);
            imageByte=readStream(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

 Socket socket = null;
        try {
            socket = new Socket(ip, 8888);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeInt(imageByte.length);//发送的时候必须添加文件的大小。
            out.write(imageByte);
            out.close();
            socket.close();
        } catch (IOException e){
            e.printStackTrace();
        }


   /**
     * @param
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;

    }

接受端:

 try {
            ServerSocket server = new ServerSocket(8888);
            Socket socket = server.accept();
            DataInputStream dos = new DataInputStream(socket.getInputStream());
            //因为发送时忘记添加文件大小。所以size的为负数报错了
            int size = dos.readInt();
            byte[] data = new byte[size];
            int len = 0;
            while (len < size) {
                len += dos.read(data, len, size - len);
            }
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            dos.close();
            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留白的云

感谢鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值