使用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字節(jié))。如果文件可能非常大,你可能需要使用其他方法來傳輸文件,例如將文件分割成多個部分并分別傳輸。