本文提供一個基於 Java Socket 通訊的圖片上傳完整代碼範例,包含客戶端發送端與伺服器端接收端的完整實現,適合初學者參考學習網路程式設計與檔案傳輸機制。
import java.io.*;
import java.net.*;
class picsend {
public static void main(String[] args) throws Exception {
// 參數檢查
if(args.length != 1) {
System.out.println("請選擇一張 .jpg 圖片");
return;
}
File file = new File(args[0]);
// 檔案存在性與格式驗證
if(!(file.exists() && file.isFile())) {
System.out.println("圖片有問題(不是檔案或不存在)");
return;
}
if(!file.getName().endsWith(".jpg")) {
System.out.println("圖片格式錯誤,請重新選擇圖片");
return;
}
if(file.length() > 1024 * 1024 * 10) {
System.out.println("圖片過大,無法上傳");
return;
}
// 建立 Socket 連線
Socket s = new Socket("192.168.33.1", 10006);
FileInputStream fis = new FileInputStream(file);
OutputStream out = s.getOutputStream();
// 分塊讀取並傳輸
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 關閉輸出流,標記傳輸結束
s.shutdownOutput();
// 接收伺服器回應
InputStream in = s.getInputStream();
byte[] response = new byte[1024];
int num = in.read(response);
System.out.println(new String(response, 0, num));
fis.close();
s.close();
}
}
// 處理執行緒類
class picThread implements Runnable {
private Socket socket;
picThread(Socket socket) {
this.socket = socket;
}
public void run() {
int count = 1;
String clientIP = socket.getInetAddress().getHostAddress();
System.out.println(clientIP + ".............connect");
try {
InputStream in = socket.getInputStream();
// 避免檔名衝突
File file = new File(clientIP + "(" + count + ")" + ".jpg");
while(file.exists()) {
file = new File(clientIP + "(" + (count++) + ")" + ".jpg");
}
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
// 發送成功回應
OutputStream out = socket.getOutputStream();
out.write("上傳成功!".getBytes());
fos.close();
socket.close();
} catch (Exception e) {
throw new RuntimeException("上傳失敗");
}
}
}
// 伺服器主類
class picrece {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(10006);
while(true) {
Socket socket = serverSocket.accept();
new Thread(new picThread(socket)).start();
}
}
}
客戶端透過 Socket 連接伺服器指定 IP 與埠號,獲得輸出流將檔案資料寫入網路;伺服器端使用 ServerSocket 監聽埠號,接受連線後為每個客戶端建立獨立執行緒處理。
採用緩衝區分塊讀寫方式,每次讀取 1KB 資料,透過 FileInputStream 讀取本地檔案,經由網路輸出流傳送;接收端使用 FileOutputStream 寫入本地磁碟。
客戶端呼叫 shutdownOutput() 關閉輸出流,向伺服器發送「流結束」信號,伺服器端 read() 返回 -1 即知傳輸完成。
伺服器端為每個連線建立獨立 Thread,實現多客戶端同時上傳互不阻塞。
程式執行後,客戶端將指定圖片上傳至伺服器,伺服器以客戶端 IP 命名儲存,並回傳「上傳成功!」訊息。若檔案不存在、格式錯誤或超過大小限制,客戶端會給出相應提示。
以上即為 Java 圖片上傳完整代碼的詳細實現與解析,希望對學習 Java 網路程式設計有所幫助。