使用Java Socket进行文件传输主要涉及到两个类:Socket
和ObjectInputStream
。以下是一个简单的示例,演示了如何使用Java Socket在客户端和服务器之间传输文件。
服务器端代码
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
Socket socket = serverSocket.accept();
System.out.println("Client connected");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
File file = (File) ois.readObject();
System.out.println("Received file: " + file.getName());
// Save the file to the server's local directory
File outputFile = new File("received_" + file.getName());
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = ois.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
ois.close();
socket.close();
serverSocket.close();
}
}
客户端代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
// Create a file to send
File file = new File("example.txt");
FileInputStream fis = new FileInputStream(file);
// Send the file name and length to the server
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
oos.writeInt(file.length());
// Send the file data to the server
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
oos.write(buffer, 0, bytesRead);
}
oos.close();
fis.close();
socket.close();
}
}
注意事项:
Integer.MAX_VALUE
(即2^31 - 1字节)。如果文件可能非常大,你可能需要使用其他方法来传输文件,例如将文件分割成多个部分并分别传输。