客戶端:
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
31
32
33
34
35
36
37
38
39
40
41
|
package cn.itcast.uploadpicture.demo; import java.io.bufferedinputstream; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.printstream; import java.net.socket; import java.net.unknownhostexception; public class uploadpicclient { public static void main(string[] args) throws unknownhostexception, ioexception { // 1、建立客戶端的socket服務 socket s= new socket( "192.168.1.216" , 10012 ); // 2、獲取圖片資源 bufferedinputstream burin= new bufferedinputstream( new fileinputstream( "f:\\cloudmusic\\羅大佑,黃霑,徐克 - 滄海一聲笑.mp3" )); // 3、獲取socket輸出流 printstream pso= new printstream(s.getoutputstream(), true ); // 4、將數據寫入到輸出流 byte []buff= new byte [ 1024 ]; int len=- 1 ; while ((len=burin.read(buff))!=- 1 ) { pso.write(buff, 0 , len); } s.shutdownoutput(); // 5、獲取服務端的返回的數據 inputstream is=s.getinputstream(); byte []buffin= new byte [ 1024 ]; int lenth=is.read(buffin); string str= new string(buffin, 0 ,lenth); system.out.println(str); // 6、關閉流 s.close(); burin.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
25
26
27
28
29
30
31
32
33
34
35
36
|
package cn.itcast.uploadpicture.demo; import java.io.bufferedinputstream; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.printstream; import java.net.serversocket; import java.net.socket; public class uploadpicserver { public static void main(string[] args) throws ioexception { serversocket ss= new serversocket( 10012 ); socket s=ss.accept(); system.out.println(s.getinetaddress().gethostaddress()+ "connnected......." ); bufferedinputstream burin= new bufferedinputstream(s.getinputstream()); file file= new file( "serve.mp3" ); if (!file.exists()) file.mkdirs(); printstream ps= new printstream( new fileoutputstream(file), true ); byte []buff= new byte [ 1024 ]; int len=- 1 ; while ((len=burin.read(buff))!=- 1 ) { ps.write(buff, 0 , len); } printstream psout= new printstream(s.getoutputstream(), true ); psout.println( "上傳成功" ); ss.close(); s.close(); ps.close(); } } |
總結
以上所述是小編給大家介紹的java 客戶端向服務端上傳mp3文件數據的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/TDOA1024/article/details/82840160