Translate

Sunday, December 11, 2022

peer-to-peer file transfer between two Android devices


Here is an example of how to implement a peer-to-peer file transfer between two Android devices:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class P2PFileTransfer {
private static final int BUFFER_SIZE = 8192; // 8KB buffer size

public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: P2PFileTransfer <file_to_send> <destination_ip>");
return;
}

String fileToSendPath = args[0];
String destinationIp = args[1];

File fileToSend = new File(fileToSendPath);
if (!fileToSend.exists()) {
System.out.println("Error: File does not exist: " + fileToSendPath);
return;
}

try {
// Open a socket connection to the destination IP
Socket socket = new Socket();
socket.connect(new InetSocketAddress(destinationIp, P2P_FILE_TRANSFER_PORT));

// Get the output stream from the socket
OutputStream outputStream = socket.getOutputStream();

// Read the file to be sent from disk and write it to the output stream
try (InputStream fileInputStream = new BufferedInputStream(new FileInputStream(fileToSend))) {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}

// Close the socket
socket.close();
} catch (IOException e) {
System.out.println("Error: Failed to send file: " + e.getMessage());
}
}
}

To receive the file on the other Android device, you can use a similar approach but with a ServerSocket instead of a Socket. The following code listens for incoming connections on port P2P_FILE_TRANSFER_PORT and saves the received file to disk:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class P2PFileReceiver {
private static final int BUFFER_SIZE = 8192; // 8KB buffer size

public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: P2PFileReceiver <save_file_path>");
return;
}

String saveFilePath = args[0];
File saveFile = new File(saveFilePath);


written by GPT3 + technoshaman001