Socket으로 데이터를 주고 받기 위해선 in, out stream 을 사용하여 주고 받는 방법을 사용합니다.
소켓 connect 구간은 생략하고 stream 이동 부분만 간략히 정리해봤습니다.
하나의 파일 전송
Android 데이터 전송할 경우입니다.
try{ PrintWriter out = new PrintWriter(new BufferedWriter(new out.println(msg);
int readBytes; totalReadBytes += readBytes;
|
SERVER 데이터 받을 경우입니다.
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
|
파일 여러개 전송
이번엔 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문 돕니다. 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.flush(); |
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(); } } |
파일 여러개 전송하는 것에 대해선 속도 개선이 필요합니다.
'프로그래밍 > android' 카테고리의 다른 글
안드로이드 JNI 사용하기(NDK 설치 및 JNI 환경설정) (0) | 2017.01.31 |
---|---|
Android monkey test 활용하기(adb명령어) (0) | 2017.01.20 |
Android 외부 저장소 관련 PERMISSION 설정 (0) | 2017.01.12 |
안드로이드, 자바 Socket file 여러개 전송-socket open,close() (0) | 2017.01.10 |
안드로이드 오버레이 권한 설정창 이동 (0) | 2016.12.28 |
안드로이드 값 저장 SharedPreferences (2) | 2016.12.27 |
마우스,키보드 어플 추천 (0) | 2016.12.26 |
애드몹 계정 정지 (7) | 2016.12.20 |