Socket으로 데이터를 주고 받기 위해선 in, out stream 을 사용하여 주고 받는 방법을 사용합니다.


소켓 connect 구간은 생략하고 stream 이동 부분만 간략히 정리해봤습니다.



하나의 파일 전송


Android 데이터 전송할 경우입니다.


 try{

        PrintWriter out = new PrintWriter(new BufferedWriter(new
        OutputStreamWriter(sock.getOutputStream())), true);
                       

                       out.println(msg);
                       out.flush();


                    System.out.println("데이터찾는중");


                       DataInputStream dis = new DataInputStream(new
        FileInputStream(new File(Environment.getExternalStorageDirectory(), msg))); //읽을 파일 경로 적어 주시면 됩니다.


                       DataOutputStream dos = new
        DataOutputStream(sock.getOutputStream());


                       byte[] buf = new byte[1024];
                       
                       long totalReadBytes = 0;

                       int readBytes;
                       while ((readBytes = dis.read(buf)) > 0) { //길이 정해주고 딱 맞게 서버로 보냅니다.
                        dos.write(buf, 0, readBytes);

                        totalReadBytes += readBytes;
                       }


                       dos.close();
                   }
                   catch(Exception e){
                       e.printStackTrace();
                   } 



SERVER  데이터 받을 경우입니다.


 

  BufferedReader in = new BufferedReader(new

  InputStreamReader(sock.getInputStream()));


                 String str = in.readLine();
                 System.out.println("수신중인 파일 이름 : " + str);
                 File f = new File("C:\\data\\", str);
                 FileOutputStream output = new FileOutputStream(f);
                 byte[] buf = new byte[1024]; 
                 
                 int readBytes;
                 
                 
                 while ((readBytes = sock.getInputStream().read(buf)) != -1) { //보낸것을 딱맞게 받아 write 합니다.
                  output.write(buf, 0, readBytes);
                  
                    }
                 
                 in.close();
                 output.close();
                 System.out.println(str+"수신완료");
             }
             catch(Exception e){
                 System.out.println("서버 에러!!");
                 e.printStackTrace();
             } 


 


파일 여러개 전송


이번엔 Android 에서 받는 것으로 구현해 보았습니다.


Android에서 파일 여러개 받기


 public void get_fileMessage(){

  try {
  

 BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());

   DataInputStream dis = new DataInputStream(bis);


   int filesCount = dis.readInt();  //파일 갯수 읽음

   File[] files = new File[filesCount]; // 파일을 read한 것 받아 놓습니다.


   for (int i = 0; i < filesCount; i++) {   //파일 갯수 만큼 for문 돕니다.
    long fileLength = dis.readLong();    //파일 길이 받습니다.
    String fileName = dis.readUTF();     //파일 이름 받습니다.


    System.out.println("수신 파일 이름 : " + fileName);


    files[i] = new File(STRSAVEPATH, fileName);      

    FileOutputStream fos = new FileOutputStream(files[i]); // 읽은 파일들 폰에서 지정한 폴더로 내보냅니다.


    BufferedOutputStream bos = new BufferedOutputStream(fos);

    for (int j = 0; j < fileLength; j++) //파일 길이 만큼 읽습니다.
     bos.write(bis.read());

    bos.flush();
   }
   
   //dis.close();
  } catch (Exception e) {
   System.out.println("서버 에러!!");
   e.printStackTrace();
  }
 } 


Server에서 파일 여러개 주기


 public static void send_file() throws IOException 

{

File[] files = new File(path).listFiles(); // path경로에있는 파일 모두 읽어들임

try { 

 

BufferedOutputStream bos = new BufferedOutputStream(

JavaSocketServer.aSocket.getOutputStream());

DataOutputStream dos = new DataOutputStream(bos);

 

dos.writeInt(files.length);  //파일 갯수 출력합니다.

 

for (File file : files) {

long length = file.length();

dos.writeLong(length);    //파일 길이 출력합니다.

 

String name = file.getName();

 

System.out.println("Path=" + file.getName()); //파일 이름 출력합니다.

dos.writeUTF(name);

 

FileInputStream fis = new FileInputStream(file);

BufferedInputStream bis = new BufferedInputStream(fis);

 

int theByte = 0;

while ((theByte = bis.read()) != -1) // BufferedInputStream으로

// 클라이언트에 보내기 위해 write함니다.

{

// System.out.println(file.getName()+"보냄");

bos.write(theByte);

}

//bos.flush();

System.out.println("송신완료");

//bis.close();

}

dos.flush();

 

} catch (Exception e) {

e.printStackTrace();

}

}




파일 여러개 전송하는 것에 대해선 속도 개선이 필요합니다.



+ Recent posts