1. 程式人生 > 其它 >用Socket套接字傳送和接收檔案(中間用陣列存取)

用Socket套接字傳送和接收檔案(中間用陣列存取)

建立服務端:

public class TcpFileServer {
 public static void main(String[] args) throws Exception {
   //1建立ServerSocket
   ServerSocket listener=new ServerSocket(9999);
  
//2偵聽,接收客戶端請求   System.out.println("伺服器已啟動.........");   Socket socket=listener.accept();
  
//3獲取輸⼊流   InputStream is=socket.getInputStream();
  
//4邊讀取,邊儲存   FileOutputStream fos=new FileOutputStream("d:\\002.jpg");   byte[] buf=new byte[1024*4];   int count=0;   while((count=is.read(buf))!=-1) {     fos.write(buf,0,count);   }
  
//5關閉   fos.close();   is.close();   socket.close();   listener.close();   System.out.println("接收完畢"); } }

建立傳送端(客戶端):

public class TcpFileClient {
 public static void main(String[] args) throws Exception {

     //1建立Socket
     Socket socket=new Socket("192.168.0.103", 9999);

     //2獲取輸出流
     OutputStream os=socket.getOutputStream();

    //3邊讀取⽂件,邊傳送
     FileInputStream fis=new FileInputStream("d:\\001.jpg");
     byte
[] buf=new byte[1024*4]; int count=0; while((count=fis.read(buf))!=-1) { os.write(buf,0,count); } //4關閉 fis.close(); os.close(); socket.close(); System.out.println("傳送完畢"); } }