使用Java实现在同一个wifi下两台电脑双向一来一回的传输文件
时间: 2023-07-16 10:13:42 浏览: 78
实现在同一个wifi下两台电脑双向一来一回的传输文件,可以考虑使用Socket编程。以下是一个简单的Java程序示例:
1. 服务端代码
```java
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server started.");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getInetAddress().getHostAddress());
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] buffer = new byte[1024];
int len;
// 读取客户端发送的文件名
len = in.read(buffer);
String fileName = new String(buffer, 0, len);
// 发送服务器上的文件到客户端
File file = new File(fileName);
FileInputStream fileIn = new FileInputStream(file);
while ((len = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
fileIn.close();
socket.close();
}
}
}
```
2. 客户端代码
```java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("192.168.0.100", 9999);
System.out.println("Connected to server.");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
String fileName = reader.readLine();
// 发送文件名到服务器
out.write(fileName.getBytes());
// 从服务器接收文件并保存到本地
byte[] buffer = new byte[1024];
int len;
FileOutputStream fileOut = new FileOutputStream("received_" + fileName);
while ((len = in.read(buffer)) > 0) {
fileOut.write(buffer, 0, len);
}
fileOut.close();
socket.close();
}
}
```
注意:在运行代码前需要先确定两台电脑在同一个wifi下,且需要替换上述代码中的IP地址为服务端所在电脑的IP地址。
阅读全文