1. 程式人生 > 其它 >編寫客戶端程式, 客戶端上傳.txt檔案(需要對檔案型別進行判斷), 伺服器端用於接收檔案(採用多執行緒), 檔案上傳成功, 服務端給客戶端一個反饋: 檔案上傳成功.

編寫客戶端程式, 客戶端上傳.txt檔案(需要對檔案型別進行判斷), 伺服器端用於接收檔案(採用多執行緒), 檔案上傳成功, 服務端給客戶端一個反饋: 檔案上傳成功.

技術標籤:基礎程式碼socket多執行緒

編寫客戶端程式, 客戶端上傳.txt檔案(需要對檔案型別進行判斷), 伺服器端用於接收檔案(採用多執行緒), 檔案上傳成功, 服務端給客戶端一個反饋: 檔案上傳成功.

在這裡插入圖片描述

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class UpServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new
ServerSocket(13770); while (true) { Socket s = ss.accept(); new Thread(() -> { try { BufferedInputStream bis = new BufferedInputStream(s.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(System.currentTimeMillis() + ".txt")); byte[] bys = new byte[1024 * 8]; int len ; while ((len= bis.read(bys)) != -1) { bos.write(bys, 0, len); bos.flush(); }
//給出反饋 BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bwServer.write("檔案上傳成功"); bwServer.flush(); bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } } } public class UpClient { public static void main(String[] args) { Socket s = null; BufferedInputStream bis = null; try { s = new Socket("127.0.0.1",13770); File file = new File("jianda\\People.txt"); if (!file.exists() || !file.isFile() || !file.getName().endsWith("txt")){ System.out.println("檔案路徑不對"); return; } bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream()); byte[] bys = new byte[1024 * 8]; int len; while ((len = bis.read(bys)) != -1) { bos.write(bys,0,bys.length); bos.flush(); } s.shutdownOutput(); BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream())); String data = brClient.readLine(); //等待讀取資料 System.out.println("伺服器端反饋: " + data); brClient.close(); }catch (IOException e1){ e1.printStackTrace(); } } }