場景
Java中Socket通信-服務端和客戶端雙向傳輸字符串實現:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108488556
在上面實現服務端與客戶端雙向的通信傳輸字符串之后,客戶端怎樣向服務端發送照片。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
首先在服務端的java項目中新建一個接收照片的方法
//服務端接收來自客戶端發送的照片 public static void getImageFromClient() throws IOException { byte[] byteArray = new byte[2048]; ServerSocket serverSocket = new ServerSocket(8088); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); int readLength = inputStream.read(byteArray); FileOutputStream imageOutputStream = new FileOutputStream(new File("D:\\badao.png")); while (readLength !=-1) { imageOutputStream.write(byteArray,0,readLength); readLength = inputStream.read(byteArray); } imageOutputStream.close(); inputStream.close(); socket.close(); serverSocket.close(); }
然后在main方法中調用該方法。
這里指定的照片的路徑就是獲取服務端發來之后存儲的路徑。
然后在客戶端新建發送照片的方法
//客戶端發送照片到服務端 public static void sendImageToServer() throws IOException { String imageFile = "C:\\Users\\admin6\\Desktop\\gzh.png"; FileInputStream imageStream = new FileInputStream(new File(imageFile)); byte[] byteArray = new byte[2048]; System.out.println("socket begin =" + System.currentTimeMillis()); Socket socket = new Socket("localhost",8088); System.out.println("socket end ="+System.currentTimeMillis()); OutputStream outputStream = socket.getOutputStream(); int readLength = imageStream.read(byteArray); while (readLength!=-1) { outputStream.write(byteArray,0,readLength); readLength = imageStream.read(byteArray); } outputStream.close(); imageStream.close(); socket.close(); }
這里的圖片路徑是要發送給服務端的照片的路徑。
然后在main方法中調用該方法。
首先運行服務端的main方法,然后運行客戶端的main方法,之后去D盤下就會接收到bao.png這張照片了。