发送使用在Android的插座文件 [英] Sending File using sockets in android

查看:82
本文介绍了发送使用在Android的插座文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道基本的socket编程。 我有一个code发送使用套接字在Android的字符串。 我想学习如何使用两部手机之间的套接字来发送文件(MP3,图片等)。

I know basic socket programming. I have a code to send strings using sockets in android. I want to learn how to send a file (MP3,image etc) using sockets between two phones.

推荐答案

这是一些code发送一个文件。它应该就像你所期待的Andr​​oid之外。我知道我送的是相对较小的文件,所以你可能希望通过一个缓冲区,使一个以上的传递。在我的示例文件F应该只是被替换包含您的MP3或图像,或任何你想发送的文件。

This is some code to send a file. It should work just like you would expect outside of Android. I knew I was sending files that were relatively small, so you might want to make more than one pass through a buffer. The File "f" in my example should just be replaced with the File that contains your MP3 or Image or whatever you want to send.

public void sendFile() throws IOException{
    socket = new Socket(InetAddress.getByName(host), port);
    outputStream = socket.getOutputStream();
    File f = new File(path);
    byte [] buffer = new byte[(int)f.length()];
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    bis.read(buffer,0,buffer.length);
    outputStream.write(buffer,0,buffer.length);
    outputStream.flush();

}

这篇关于发送使用在Android的插座文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆