JAVA/HIGH JAVA

5/9 Homework - 네트워킹을 이용한 파일 복사

아잠만_ 2024. 5. 9. 12:44

문제

파일을 전송하는 통신 프로그램을 작성하시오.

서버가 준비되고 클라이언트가 서버에 접속하면
1) 클라이언트가 'd:/d_other/' 폴더에 있는 '코알라.jpg'파일을
    읽어서 서버로 전송한다.
2) 서버는 클라이언트가 보내온 이미지 파일 데이터를 받아서
   서버의 'd:/d_other/연습용
   
   -- 서버 프로그램 : TcpFileServer
   -- 클라이언트 : TcpFileClient


TcpFileServer

package kr.or.ddit.basic.tcp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpFileServer {
	public static void main(String[] args) {
		File saveDir = new File("d:/d_other/연습용");
		if(!saveDir.exists()) {
			saveDir.mkdirs();	// 저장할 폴더가 없으면 새로 생성한다.
		}
		
		ServerSocket server = null;
		Socket socket = null;
		BufferedInputStream bin = null;
		BufferedOutputStream bout = null;
		try {
			server = new ServerSocket(8888);
			System.out.println("서버 대기중");
			
			socket = server.accept();
			
//			BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("d:/d_other/연습용/코알라.jpg"));
			
			// 클라이언트는 전송한 파일 이름을 먼저 전송한 후
			// 파일의 내용을 읽어서 전송하는 순서로 작업이 진행
			
			// 클라이언트가 보내온 파일 이름 수신하기
			DataInputStream din = new DataInputStream(socket.getInputStream());
			String fileName = din.readUTF();
			
			File saveFile = new File(saveDir, fileName);
			
			bin = new BufferedInputStream(socket.getInputStream());
			bout = new BufferedOutputStream(new FileOutputStream(saveFile));
			
			byte[] temp = new byte[1024];
			
			int length=0;
			while((length = bin.read(temp))!=-1) {
				bout.write(temp, 0, length);
			}
			bout.flush();
			
			System.out.println("저장되었습니다");
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("오류");
		} finally {
			try {
				if(bout!=null) try {bout.close();} catch(IOException e) {}
				if(bin!=null) try {bin.close();} catch(IOException e) {}
				if(socket!=null) try {socket.close();} catch(IOException e) {}
				if(server!=null) try {server.close();} catch(IOException e) {}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
	}
}

TcpFileClient

package kr.or.ddit.basic.tcp;

import java.awt.Panel;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;


public class TcpFileClient {
	public static void main(String[] args) {
		Socket socket = null;
		
		DataOutputStream dout = null;
		BufferedInputStream bin = null;
		BufferedOutputStream bout = null;
		System.out.println("서버에 접속합니다");
		try {
			socket = new Socket("localhost", 8888);
			System.out.println("서버에 연결되었습니다");
			
			
			
			// 이미지 파일 지정하기
			JFileChooser chooser = new JFileChooser();
			FileNameExtensionFilter img = new FileNameExtensionFilter("이미지 파일", new String[] { "jpg", "png", "gif" });
			chooser.addChoosableFileFilter(img);
			
			chooser.setCurrentDirectory(new File("D:\\A_TeachingMaterial\\05_JQuery\\webpro\\WebContent\\images"));
			File sourceFile = null;
			int result = chooser.showOpenDialog(new Panel());
			if (result == JFileChooser.APPROVE_OPTION) { // 열기나 저장버튼 눌렀는 지 확인
				sourceFile = chooser.getSelectedFile();
				if(sourceFile==null) {
					System.out.println("복사할 원본 파일이 선택되지 않았습니다");
					System.out.println("복사 작업 중지..");
					return;
				}
			}
			
			
//			File sourceFile = new File("d:/d_other/코알라.jpg");
			
			// 파일 이름 보내기
			dout = new DataOutputStream(socket.getOutputStream());
			dout.writeUTF(sourceFile.getName());
			
			System.out.println(sourceFile.getName());
			
			// 파일 내용을 읽어서 서버로 전송
			bin = new BufferedInputStream(new FileInputStream(sourceFile));
			bout = new BufferedOutputStream(socket.getOutputStream());
			
			byte[] temp = new byte[1024];
			int c = 0;
			while((c = bin.read(temp))!=-1) {
				bout.write(temp,0,c);
			}
			bout.flush();
			System.out.println("사진정보를 보냈습니다");
			System.out.println("연결을 종료합니다");
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("파일 전송작업 실패");
		} finally {
			if(dout!=null) try {dout.close();} catch(IOException e) {}
			if(bout!=null) try {bout.close();} catch(IOException e) {}
			if(bin!=null) try {bin.close();} catch(IOException e) {}
			if(socket!=null) try {socket.close();} catch(IOException e) {}
		}
	}
}