JavaTCP上傳圖片代碼實(shí)例
1.客戶端代碼
public class UploadPicClient {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
//1,創(chuàng)建客戶端socket
Socket s = new Socket("localhost",10088);
//2,讀取客戶端要上傳的圖片文件
FileInputStream fis = new FileInputStream("D:\\workspace\\day2019.1.17\\lanjing.jpg");
//3,獲取Socket輸出流,將讀到的圖片的數(shù)據(jù)發(fā)送到服務(wù)端
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1021];
int len =0;
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
//告訴服務(wù)端說:這邊的數(shù)據(jù)發(fā)送完畢讓服務(wù)端停止讀取
s.shutdownOutput();
//讀取服務(wù)端發(fā)回的內(nèi)容
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);
//關(guān)閉資源
fis.close();
s.close();
}
}
2.服務(wù)端代碼
public class UploadPicSever {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//創(chuàng)建tcp的socket服務(wù)端
ServerSocket ss = new ServerSocket(10088);
//獲取客戶端
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+".....connected");
//讀取客戶端發(fā)來的數(shù)據(jù)
InputStream in = s.getInputStream();
//將讀取到的數(shù)據(jù)存儲(chǔ)到一個(gè)文件中。
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輸出流,將上傳成功字樣發(fā)送給客戶端
OutputStream out = s.getOutputStream();
out.write("上傳成功".getBytes());
fos.close();
s.close();
ss.close();
}
上傳后和上傳前的圖片:

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
SpringSecurity中內(nèi)置過濾器的使用小結(jié)
SpringSecurity通過其復(fù)雜的過濾器鏈機(jī)制,為Java應(yīng)用提供了全面的安全防護(hù),本文主要介紹了SpringSecurity中內(nèi)置過濾器的使用小結(jié),感性的可以了解一下2025-03-03
eclipse中maven的pom.xml文件中增加依賴的方法
日 在Maven項(xiàng)目中,可以使用pom.xml文件來添加依賴包,本文主要介紹了eclipse中maven的pom.xml文件中增加依賴的方法,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
解決jackson反序列化失敗InvalidFormatException:Can not dese
這篇文章主要介紹了解決jackson反序列化失敗InvalidFormatException:Can not deserialize value of type java.util.Date問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Springcloud實(shí)現(xiàn)服務(wù)多版本控制的示例代碼
這篇文章主要介紹了Springcloud實(shí)現(xiàn)服務(wù)多版本控制的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
使用Java8進(jìn)行分組(多個(gè)字段的組合分組)
本文主要介紹了使用Java8進(jìn)行分組(多個(gè)字段的組合分組),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
spring boot配合前端實(shí)現(xiàn)跨域請(qǐng)求訪問
本篇文章主要介紹了spring boot配合前端實(shí)現(xiàn)跨域請(qǐng)求訪問,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04

