1.客戶端代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class uploadpicclient { public static void main(string[] args) throws unknownhostexception, ioexception { // todo auto-generated method stub //1,創建客戶端socket socket s = new socket( "localhost" , 10088 ); //2,讀取客戶端要上傳的圖片文件 fileinputstream fis = new fileinputstream( "d:\\workspace\\day2019.1.17\\lanjing.jpg" ); //3,獲取socket輸出流,將讀到的圖片的數據發送到服務端 outputstream out = s.getoutputstream(); byte [] buf = new byte [ 1021 ]; int len = 0 ; while ((len=fis.read(buf))!=- 1 ){ out.write(buf, 0 ,len); } //告訴服務端說:這邊的數據發送完畢讓服務端停止讀取 s.shutdownoutput(); //讀取服務端發回的內容 inputstream in = s.getinputstream(); byte [] bufin = new byte [ 1024 ]; int lenin = in.read(buf); string text = new string (buf, 0 ,lenin); system.out.println(text); //關閉資源 fis.close(); s.close(); } } |
2.服務端代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class uploadpicsever { public static void main(string[] args) throws ioexception { // todo auto-generated method stub //創建tcp的socket服務端 serversocket ss = new serversocket( 10088 ); //獲取客戶端 socket s = ss.accept(); string ip = s.getinetaddress().gethostaddress(); system.out.println(ip+ ".....connected" ); //讀取客戶端發來的數據 inputstream in = s.getinputstream(); //將讀取到的數據存儲到一個文件中。 file dir = new file( "d:\\workspace\\day2019.1.17" ); if (!dir.exists()){ dir.mkdirs(); } file file = new file(dir, "blue.jpg" ); fileoutputstream fos = new fileoutputstream(file); byte [] buf = new byte [ 1024 ]; int len = 0 ; while ((len=in.read(buf))!=- 1 ){ fos.write(buf, 0 ,len); } //獲取socket輸出流,將上傳成功字樣發送給客戶端 outputstream out = s.getoutputstream(); out.write( "上傳成功" .getbytes()); fos.close(); s.close(); ss.close(); } |
上傳后和上傳前的圖片:
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/lzq1326253299/article/details/86528524