1. 程式人生 > 實用技巧 >基於UDP用JAVA實現客戶端和服務端通訊

基於UDP用JAVA實現客戶端和服務端通訊

案例模型分析:

基於TCP實現,一個Clinet(傳送端)向,一個Server(接收端)上傳圖片檔案的功能。要求,客戶端上上傳的圖片路徑,需要從配置檔案.properties檔案中讀取

為了簡化並可視結果:客戶端和服務端,用本機ip上兩個埠模擬即可;

定義Socket的時候,本機埠是OS隨機分配的;

傳送的檔案型別是圖片,用位元組流(圖片可能很大,這裡用緩衝流包裝)

由於伺服器端套接字輸入流是一個阻塞方法,客戶端傳送完資料後,需要用shutdown方法關閉客戶端套接字輸出流,這樣服務端就不會一直阻塞等待新的輸入;

客戶端:

package netTCP;

import java.io.*;
import java.net.Socket; public class Clinet { public static void main(String args[]) throws IOException { //獲取文字內容,得到目標檔案的路徑 String filepathtoUpload = getPath(); System.out.println("獲得要上傳的檔案所在路徑是: "+filepathtoUpload); //定義客戶端埠(目的ip,目的埠) Socket socket = new Socket("127.0.0.1",9991);
//定義緩衝輸入流,準備讀入圖片的位元組緩衝陣列 BufferedInputStream bi = new BufferedInputStream(new FileInputStream(filepathtoUpload)); byte[] buffpic= new byte[1024]; int len; //獲取客戶端傳送流,做包裝;一邊讀圖片位元組資料,一邊傳送 OutputStream out = socket.getOutputStream(); BufferedOutputStream bos
= new BufferedOutputStream(out); while((len = bi.read(buffpic))!=-1){ bos.write(buffpic,0,len); } bos.flush();//重新整理快取 socket.shutdownOutput();//禁用此套接字的輸出流,可以使伺服器端的InputStream不在阻塞 //獲取客戶端輸入流,接受檔案上傳後反饋資訊 InputStream in = socket.getInputStream(); byte [] feedBack = new byte[1024]; int lenfeedBack = in.read(feedBack); System.out.println(new String(feedBack,0,lenfeedBack)); //收到反饋資訊後,關閉套接字socket socket.close(); bi.close(); } public static String getPath() throws IOException { FileInputStream fileInputStream = new FileInputStream("G:\\JavaTestDir\\路徑有中文\\config.properties"); byte[] buffer = new byte[1024]; int len = fileInputStream.read(buffer); String s = new String(buffer,0,len); return s; } }

服務端:

package netTCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
   public static void main(String args[]) throws IOException {
       //定義服務端SeverSocker,並獲取服務端連線的socket
       ServerSocket serverSocket = new ServerSocket(9991);
       Socket socket = serverSocket.accept();

       //獲取socket輸入流,並用快取位元組流包裝;
       InputStream in = socket.getInputStream();
       BufferedInputStream bis = new BufferedInputStream(in);

       //指定一個路徑(這裡用預設路徑),定義緩衝輸出流,用於將圖片儲存到預設路徑
       FileOutputStream fo = new FileOutputStream("copy.jpg");
       BufferedOutputStream bos = new BufferedOutputStream(fo);

       //接收客戶端的資料,並寫到指定位置
       byte[] buff = new byte[1024];
       int len = 0;
       while((len = bis.read(buff))!=-1){
            bos.write(buff,0,len);
       }
        bos.flush();

       //獲取socket輸出流
       OutputStream out = socket.getOutputStream();
       //返回檔案上傳結束資訊給客戶端(中文)
       String feedbackMessage ="檔案上傳結束";
       out.write(feedbackMessage.getBytes());

       //out.close();//可不用,由客戶端關閉socket即可
       fo.close();
      // in.close();//可不用,有客戶端關閉socket即可
       socket.close();
       serverSocket.close();;
   }

}

可以看到執行完,圖片被上傳到預設路徑