基于聊天客戶(hù)端的基礎(chǔ)上的文件(txt文件)傳輸
客戶(hù)端代碼:
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,創(chuàng)建socket客戶(hù)端對(duì)象 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); } //告訴服務(wù)端,客戶(hù)端寫(xiě)完了 s.shutdownoutput(); //4,讀取服務(wù)端返回的上傳成功對(duì)象 bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream())); string str = bufin.readline(); system.out.println(str); //關(guān)閉資源 bufr.close(); s.close(); } } |
服務(wù)端代碼:
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對(duì)象 socket s = ss.accept(); //獲取ip system.out.println(s.getinetaddress().gethostaddress()+ "....conected" ); //3,獲取socket讀取流,并裝飾 bufferedreader bufin = new bufferedreader( new inputstreamreader(s.getinputstream())); //4,寫(xiě)入文件 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(); //關(guān)閉客戶(hù)端 ss.close(); //關(guān)閉服務(wù)端 } |
要注意的是tcp傳輸中,一定要先運(yùn)行服務(wù)端再運(yùn)行客戶(hù)端。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/lzq1326253299/article/details/86526556