如何实现基于Socket的文件传输?

使用Socket可以实现基于网络的文件传输。以下是一个简单的Java代码示例:

服务器端:

ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
    fileOutputStream.write(buffer, 0, length);
}
fileOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();

客户端:

Socket socket = new Socket("127.0.0.1", 8888);
File file = new File("test.txt");
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, length);
}
outputStream.flush();
fileInputStream.close();
socket.close();