我知道基本的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发送一个文件。它应该就像你所期待的Android之外。我知道我送的是相对较小的文件,所以你可能希望通过一个缓冲区,使一个以上的传递。在我的示例文件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();
}