【Java源碼】TCP協議之服務端與客戶端文件傳輸

 

---------------------------------------------------------------------------------------------------------------------------------------

服務端

---------------------------------------------------------------------------------------------------------------------------------------

 

package socket.file;

import java.io.*;
import java.net.*;

public class FileServer {
 private static String basePath;

 public static void main(String[] args){

  ServerSocket ss = null;
  Socket sc = null;
  FileOutputStream fos = null;
  try {
   ss = new ServerSocket(2222);//創建端口
   sc = ss.accept();//進入阻塞
   BufferedInputStream bis = new BufferedInputStream(sc.getInputStream());//反衝區
   byte[] b = new byte[512];//接收文件名
   bis.read(b);//讀取文件名
   fos = new FileOutputStream("src/");//目標路徑

   String fileName = new File(new String(b).trim()).getName();
   String filePath = basePath + fileName;

   for (int k = bis.read(); k != -1; fos.write(b), k = bis.read())
    ;
   fos.flush();
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
  try {
   if (null != fos) {
    fos.close();
   }
   if (null != fos) {
    fos.close();
   }
   if (null != sc) {
    sc.close();
   }
   if (null != ss) {
    ss.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  }

 }

}

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------

客戶端

---------------------------------------------------------------------------------------------------------------------------------------

package socket.file;

import java.io.*;
import java.net.*;

public class FileClient {

 public static void main(String[] args) {
  Socket cs = null;
  BufferedOutputStream bos = null;
  FileInputStream fis = null;
  try {
   cs = new Socket("127.0.0.1", 2222);
   String filePath = "H:/Photos.jpg";
   bos = new BufferedOutputStream(cs.getOutputStream());
   byte[] b = new byte[512];
   System.arraycopy(filePath.getBytes(), 0, b, 0,
     filePath.getBytes().length);// src:源數組;DestPos:目標數組;dest:;destPos:;

   bos.write(b);
   fis = new FileInputStream(filePath);
   for (int k = fis.read(); k != -1; bos.write(k), k = fis.read())
    ;
   bos.flush();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (null != bos)
     bos.close();
    if (null != fis)
     fis.close();
    if (null != cs)
     cs.close();
   } catch (IOException e) {
    e.printStackTrace();
   }

  }
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章