我了解基本的套接字编程。 我有一个在 android 中使用套接字发送字符串的代码。 我想了解如何使用两部手机之间的套接字发送文件(MP3、图像等)。
最佳答案
这是一些发送文件的代码。它应该像您在 Android 之外所期望的那样工作。我知道我发送的文件相对较小,因此您可能需要多次通过缓冲区。我的示例中的文件“f”应该替换为包含 MP3 或图像或您要发送的任何内容的文件。
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 - 在android中使用socket发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332052/