1. 程式人生 > >java多執行緒,多個客戶端之間傳送檔案

java多執行緒,多個客戶端之間傳送檔案

        java通過利用TCP,Socket和ServerSocket的類,進行訊息的傳遞,。通過while(true),形成點對點的單次通訊。不過必須得等待對方的回覆,才可以進行下一步。

之後利用多執行緒,實現刷屏多次聊天。  利用這一點思路,將輸入的字串轉化成檔案。來進行檔案的傳遞,以及多使用者傳送。

package tcom.tcp.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClientReceiveThread implements Runnable {

	private String PATH;
	private Socket socket;
	public ClientReceiveThread(Socket socket,String PATH){
		this.socket = socket;
		this.PATH = PATH;
	}

	public void run() {
		System.out.println("請輸入要儲存檔案的地址:");
		String PATH1= new Scanner(System.in).next();
		File file = new File(PATH1);
		try {
			InputStream is = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			OutputStream os = new FileOutputStream(file);
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			
			String msg = null;
			while((msg=br.readLine())!=null){
				bw.write(msg);
				bw.newLine();
				bw.flush();
			}
			
			bw.close();
			br.close();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}