1、需求分析:
①客戶端向服務端上傳一個文本文件
②服務端收到文件後,反饋一個結束信息,並打印"接收數據成功"
③客戶端收到服務端的反饋後,打印"上傳文件成功"
2、客戶端:
①定義Socket、文件輸入流、Socket輸出流、Socket輸入流
②從文件輸入流讀取文件,
③將讀到的數據寫入Socket輸出流中
④關閉資源
詳細的看代碼註釋;
package day23.fileUpload;
import java.net.*;
import java.io.*;
/**
* @author Administrator @zsw 2012-7-18 上午09:21:04
*
* 需求:從客戶端上傳文本文件到服務端
*
* 客戶端上傳:
* ①定義Socket、文件輸入流、Socket輸出流、Socket輸入流
* ②從文件輸入讀取文件,
* ③將讀到的數據寫入Socket輸出流中
* ④關閉資源
*/
public class FileClient {
public static void main(String[] args) throws Exception{
//①:定義資源
Socket s=new Socket("127.0.0.1",10006);
BufferedReader bufr=new BufferedReader(new FileReader("D:\\1.txt"));
//字符流轉換成字節流
BufferedWriter bufout=new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
// PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader bufin=new BufferedReader(
new InputStreamReader(s.getInputStream()));
//②上傳數據
String line=null;
while((line=bufr.readLine())!=null){
System.out.println(line);
bufout.write(line);
bufout.newLine();
bufout.flush();
}
//③告訴服務器,客戶端已經傳完了。並接收服務端的反饋信息
s.shutdownOutput();//關閉客戶端的輸出流,相當於在流中寫-1
String line2=null;
while((line2=bufin.readLine())!=null){
if("success".equals(line2)){
System.out.println("上傳文件成功!");
break;
}
}
//④關閉資源
bufr.close();
s.close();
}
}
3、服務端:
①、定義資源:ServerSocket、流
②接收客戶端的數據,並將數據寫入文件
③接收完後,給客戶端反饋"success"
④關閉資源
詳細的見代碼註釋:
package day23.fileUpload;
import java.io.*;
import java.net.*;
/**
* @author Administrator @zsw 2012-7-18 上午09:43:46
*
* 服務端:
* 1、定義資源:ServerSocket、流
* 2、接收客戶端的數據,並將其寫入文件
* 3、接收完後,給客戶端反饋"success"
* 4、關閉資源
*
* 總結:
* ①使用了readLine這樣的阻塞方法,由於它讀數據丟棄了換行的數據
* 所有在寫到流中的時候要添加換行數據
* ②整個流寫完了,要做一個結束標記,這樣結束端就可以結束
* 使用s.shutdownOutput() ,即調用Socket的shutdownOutput方法
* 往流裏面添加一個-1,是readLine()=null,可以結束掉
*/
public class FileServer {
public static void main(String[] args) throws Exception {
//①資源
ServerSocket ss=new ServerSocket(10006);
Socket s=ss.accept();
//文件輸出流
BufferedWriter bufw=new BufferedWriter(new FileWriter("D:\\tx\\1.txt"));
//Socket 輸出輸入
BufferedReader bufin=new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter bufout=new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
String ip=s.getLocalAddress().getHostAddress();
System.out.println(ip+" ....connnect ");
//②:讀數據、寫到文件、判斷結束、反饋成功
String line=null;
/*
* 服務端收不到line=null的情況,必須在流中添加結束標記
* s.shutdownOutput();
* 關閉客戶端的輸出流,相當於在流中寫-1,line就可以=null
*/
//獲取標記符(即時間值)
while((line=bufin.readLine())!=null){
bufw.write(line);
bufw.newLine();
bufw.flush();
}
System.out.println("數據接收成功!");
bufout.write("success");
bufout.newLine();
bufout.flush();
s.shutdownOutput();
//不必資源
bufw.close();
s.close();
ss.close();
}
}
4、問題總結
①使用了readLine這樣的阻塞方法,由於它讀數據丟棄了換行,所以在寫到流中的時候要添加換行數據,否則會一直等待。
②整個流寫完了,要做一個結束標記,這樣結束端就可以結束,
使用s.shutdownOutput() ,即調用Socket的shutdownOutput方法往流裏面添加一個-1,使readLine()=null,可以結束掉