生成一个Android studio两设备通过socket进行文件传输的代码
时间: 2024-05-02 15:20:04 浏览: 49
您好!以下是一个简单的示例代码,可以实现Android Studio两设备通过socket进行文件传输。
客户端代码:
```java
public class FileClient {
public static final String SERVER_IP = "192.168.1.100"; // 服务器IP
public static final int SERVER_PORT = 8888; // 服务器端口号
public static void main(String[] args) {
try {
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
// 发送文件
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(new File("D:/test.png"));
byte[] buffer = new byte[1024];
int length = 0;
while ((length = fis.read(buffer, 0, buffer.length)) != -1) {
dos.write(buffer, 0, length);
dos.flush(); // 清空缓存区数据,防止数据丢失
}
fis.close();
dos.close();
socket.close();
System.out.println("文件发送完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
服务端代码:
```java
public class FileServer {
public static final String SAVE_PATH = "D:/received/test.png"; // 文件保存路径
public static final int SERVER_PORT = 8888; // 服务端口号
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,开始接收文件...");
// 接收文件
DataInputStream dis = new DataInputStream(socket.getInputStream());
File file = new File(SAVE_PATH);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = dis.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, length);
fos.flush(); // 清空缓存区数据,防止数据丢失
}
dis.close();
fos.close();
socket.close();
serverSocket.close();
System.out.println("文件接收完成,保存路径为:" + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
希望以上代码能够帮助您!
阅读全文