import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) {
int port = 8080;
try (ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
FileOutputStream fos = new FileOutputStream("receivedFile.txt")) {
System.out.println("服务器已启动,等待客户端连接...");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("文件接收成功。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) {
String host = "localhost";
int port = 8080;
String filePath = "testFile.txt";
try (Socket socket = new Socket(host, port);
FileInputStream fis = new FileInputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream())) {
System.out.println("客户端已连接至服务器,开始发送文件...");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
System.out.println("文件发送成功。");
} catch (IOException e) {
e.printStackTrace();
}
}
}