我正在编写代码,我想将mp4文件发送到另一台Android设备。我已经通过Wifi连接两个Androids并从一个简单的循环中写入1-20,另一个Android设备读取并显示发送的数字。
这是“发件人”的有趣部分:
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, port);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
for (int i = 1; i < 20; i++) {
out.println(i);
i=i++;
和“接收者”:
serverSocket = new ServerSocket(SERVERPORT);
// listen for incoming clients
Socket client = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()),8*1024);
这很棒!但我想将文件从一个设备发送到另一个设备而不是int。我该如何制作这个?????
答案 0 :(得分:1)
您需要通过某种数据格式将数据打包到流中。一种方法是使用常用的MIME数据格式,这种格式通常用于在电子邮件中发送附件。
我已回答了有关在the following SO Question - android add filename to bytestream中使用此格式通过套接字发送二进制文件的其他问题。您可以查看该问题的已接受答案。
供您参考,我刚刚从下面的问题复制了通过套接字发送和接收的代码。
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
String filename=path.substring(path.lastIndexOf("/")+1);
// create a multipart message
MultipartEntity multipartContent = new MultipartEntity();
// send the file inputstream as data
InputStreamBody isb = new InputStreamBody(new FileInputStream(f), "image/jpeg", filename);
// add key value pair. The key "imageFile" is arbitrary
multipartContent.addPart("imageFile", isb);
multipartContent.writeTo(out);
out.flush();
out.close();
使用作为JavaMail一部分的MimeBodyPart来读取下面的代码。
MimeMultipart multiPartMessage = new MimeMultipart(new DataSource() {
@Override
public String getContentType() {
// this could be anything need be, this is just my test case and illustration
return "image/jpeg";
}
@Override
public InputStream getInputStream() throws IOException {
// socket is the socket that you get from Socket.accept()
BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
return inputStream;
}
@Override
public String getName() {
return "socketDataSource";
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
});
// get the first body of the multipart message
BodyPart bodyPart = multiPartMessage.getBodyPart(0);
// get the filename back from the message
String filename = bodyPart.getFileName();
// get the inputstream back
InputStream bodyInputStream = bodyPart.getInputStream();
// do what you need to do here....
答案 1 :(得分:0)
Google推出了一个开源项目 ,您可以查看它并大致了解如何在它们之间连接设备和共享文件。
以下是链接:android-fileshare