基于聊天客戶端的基礎上的文件(txt文件)傳輸
客戶端代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class uploadclient { public static void main(string[] args) throws unknownhostexception, ioexception { // todo auto-generated method stub //1,創建socket客戶端對象 socket s = new socket( "localhost" , 10005 ); //2,讀取本地文件 bufferedreader bufr = new bufferedreader( new filereader( "c:\\新建文件夾\\client.txt" )); //3,socket流 printwriter out = new printwriter(s.getoutputstream(), true ); string line = null ; while ((line=bufr.readline())!= null ){ out.println(line); } //告訴服務端,客戶端寫完了 s.shutdownoutput(); //4,讀取服務端返回的上傳成功對象 bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream())); string str = bufin.readline(); system.out.println(str); //關閉資源 bufr.close(); s.close(); } } |
服務端代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public static void main(string[] args) throws unknownhostexception, ioexception { // todo auto-generated method stub //1, serversocket ss = new serversocket( 10005 ); //2,獲取socket對象 socket s = ss.accept(); //獲取ip system.out.println(s.getinetaddress().gethostaddress()+ "....conected" ); //3,獲取socket讀取流,并裝飾 bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream())); //4,寫入文件 bufferedwriter bufw = new bufferedwriter( new filewriter( "c:\\新建文件夾\\server.txt" )); string line = null ; while ((line=bufin.readline())!= null ){ bufw.write(line); bufw.newline(); //換行 bufw.flush(); //刷新流 } printwriter out = new printwriter(s.getoutputstream(), true ); out.println( "上傳成功" ); bufw.close(); s.close(); //關閉客戶端 ss.close(); //關閉服務端 } |
要注意的是tcp傳輸中,一定要先運行服務端再運行客戶端。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/lzq1326253299/article/details/86526556