반응형
FileSendClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import java.io.*; import java.net.*; import java.util.*; public class FileSendClient { public static void main(String[] args) { // 파일이름을 입력받기 위한 변수 Scanner scanner = new Scanner(System. in ); System.out.println( "전송할 파일이름 : " ); // 전송할 곳의 주소를 저장할 변수 String ip = "127.0.0.1" ; // 파일명을 저장할 변수 String filename = null ; // 파일의 내용을 읽을 변수 DataInputStream dis = null ; // 파일 이름 입력 받기 filename = scanner.next(); // 입력 받은 이름으로 file 객체 생성 File file = new File(filename); // 파일이 없다면 프로그램 종료 if (file.exists() == false ){ System.out.println( "파일이 존재하지 않습ㄴ디ㅏ" ); System.exit(0); } try { // UDP 소켓 생성 DatagramSocket socket = new DatagramSocket(); // 전송할 곳이 주소생성 InetAddress ia = InetAddress.getByName( "127.0.0.1" ); // 파일 전송하기 위해 start라는 문자열 전송 String str = "start" ; // 전송할 객쳋 생성 DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length); // 전송 socket.send(dp); // 파일의 냉ㅇ을 저장할 배열 byte [] by = new byte[512]; // 모든 내용을 읽어서 전송 while ( true ){ int xx = dis.read(by, 0, by.length); if (xx == -1) break ; dp = new DatagramPacket(by, xx , ia , 9875); str = "end" ; dp = new DatagramPacket(str.getBytes(), str.getBytes().length,ia,9876); socket.send(dp); dis.close(); socket.close(); } } catch (Exception e){ System.out.println(e.getMessage()); } } } |
FileReceiveServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import java.io.*; import java.net.*; public class FileReceiveServer { public static void main(String[] args) { // 문자열로 이루어진 파일을 전송받는 프로그랭 // 전송받을 UDP 소켓을 생성 try { DatagramSocket socket = new DatagramSocket(9875); System.out.println( "수신 준비 완료......." ); // 전송받은 내용을 저장할 함수 File file = null ; // 데이터를 전송받을 Stream 변수 DataOutputStream dos = null ; while ( true ){ // 전송받을 데이터 패킷 생성 DatagramPacket dp = new DatagramPacket( new byte[512], 512); // 데이터 전송받기 socket.receive(dp); // 전송받은 데이터 를 문자열료 변환 String str = new String(dp.getData()).trim(); // 전송받은 문자열이 strat 라면 받으룬비 if (str.equals( "start" )){ System.out.println( " 전송 시작 " ); // 파일 객체 생성 // 파일 쓰기 객체 새엉 dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(file))); } //end가 ㅇ면 종료 else if (str.equals( "end" )){ System.out.println( "전송완료" ); socket.close(); break ; } else { // dos에 연결된 파일에 str의 바이ㅌ 배열은 0부터 부ㅜ터 길이많큼 기록 dos.write(str.getBytes(),0,str.getBytes().length); } } dos.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } } |
'JAVA > Java' 카테고리의 다른 글
[JAVA] 간단한 UDP server, client (0) | 2014.11.18 |
---|---|
[JAVA] Thread 를 사용하여 URL 웹 파일 다운로드 (0) | 2014.11.18 |
[JAVA] 자신의 ip 확인 및 IP 출력 (0) | 2014.11.18 |
[JAVA] Multicast Server, Client (Socket) (0) | 2014.11.18 |
[JAVA] TCP Server, Client (Socket) (0) | 2014.11.18 |