수업시간 JAVA/문제

서버-클라이언트 파일 다운로드 하기+DB연동

SEOKIHOUSE 2023. 5. 4. 11:57
CREATE TABLE `client` (
	`num` INT(11) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_general_ci',
	`id` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_general_ci',
	`pw` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_general_ci',
	`downfile` VARCHAR(50) NULL DEFAULT '' COLLATE 'utf8mb4_general_ci',
	PRIMARY KEY (`num`) USING BTREE
)
package practice0503okㅇ;

public class ClientTest {

	public static void main(String[] args) throws Exception {
		ClientService cs = new ClientService();
		cs.mainActice();
	}

}
package practice0503okㅇ;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClientService {
	Scanner sc = new Scanner(System.in);
	Socket socket = null;
	InputStreamReader isr = null;
	OutputStreamWriter osw = null;
	BufferedReader br = null;
	PrintWriter pw = null;
	FileWriter fw = null;
	ClientDao cd = new ClientDao();
	ClientVo now = new ClientVo(); // 현재 로그인 정보저장
	ObjectOutputStream oos = null;
	ObjectInputStream ois = null;
	
	
	public void mainActice() {
		try {
			socket = new Socket("localhost", 5000);
			isr = new InputStreamReader(socket.getInputStream());
			br = new BufferedReader(isr);
			System.out.println("서버연결완료");
			oos = new ObjectOutputStream(socket.getOutputStream());
			pw = new PrintWriter(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
			osw = new OutputStreamWriter(socket.getOutputStream());

			while (true) {
				System.out.println("1.로그인 2.회원가입 0.종료");
				int where = sc.nextInt();
				if (where == 1) {
					System.out.print("아디입력");
					String id = sc.next();
					System.out.print("비번입력");
					String pws = sc.next();
					ClientVo cv = new ClientVo();
					cv.setId(id);
					cv.setPw(pws);

					oos.writeObject(cv);
					oos.flush();
					osw.write(where);
					osw.flush();
					now = (ClientVo) ois.readObject();
					if (now != null) {
						System.out.println("로그인 성공");
						break;
					} else {
						System.out.println("로그인실패");
					}
				} else if (where == 2) {
					System.out.print("이름입력");
					String name = sc.next();
					System.out.print("아디입력");
					String id = sc.next();
					System.out.print("비번입력");
					String pws = sc.next();
					ClientVo cv = new ClientVo();
					cv.setName(name);
					cv.setId(id);
					cv.setPw(pws);

					oos.writeObject(cv);
					oos.flush();
					osw.write(where);
					osw.flush();
					System.out.println("회원가입완료");
				} else if (where == 0) {
					pw.println(where);
					pw.flush();
					break;
				} else {
					System.out.println("범위 아웃");
				}
			}

			while (true) {
				String choose = "";
				System.out.println("동물 백과사전입니다 다운받으실 파일을 선택하세요");
				System.out.print("1.고슴도치 2.다람쥐 0.종료");
				choose = sc.next();

				String nowpic = "";
				if (choose.equals("1")) {
					String title = "고슴도치";
					fileWrite(choose,title);

				} else if (choose.equals("2")) {
					String title = "다람쥐";
					fileWrite(choose,title);
				} else if (choose.equals("0")) {
					pw.println(choose);
					pw.flush();
					System.out.println("종료");
					break;
				} else {
					System.out.println("범위 벗어났음");
				}
			}

		}

		catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				isr.close();
				br.close();
				pw.close();
				oos.close();
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void fileWrite(String choose,String title) {
		String nowpic = title;
		try {
			pw.println(choose);
			pw.flush();
			// 1
			String a = br.readLine();
			
			fw = new FileWriter("["+title+"client].txt");
			fw.write(a);
			fw.flush();
			fw.close();
			System.out.println("다운완료");
			
			pw.println(nowpic);
			pw.flush();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
package practice0503okㅇ;

public class ServerTest {

	public static void main(String[] args) {
		ServiceUiService sus = new ServiceUiService();
		
		sus.acticeMain();
	}
	
}
package practice0503okㅇ;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceUiService {
	Socket socket = null;
	FileWriter fw = null;
	FileReader fr = null;
	InputStreamReader isr = null;
	BufferedReader br = null;
	PrintWriter pw = null;
	ServerSocket serverSocket = null;
	ObjectInputStream ois = null;
	ClientVo now = new ClientVo();
	ClientDao cd = new ClientDao();
	ObjectOutputStream oos = null;

	public void acticeMain() {
		try {
			serverSocket = new ServerSocket(5000);
			System.out.println("client 접속대기중..");
			socket = serverSocket.accept();
			System.out.println("client 접속완료!");
			isr = new InputStreamReader(socket.getInputStream());
			br = new BufferedReader(isr);
			pw = new PrintWriter(socket.getOutputStream());
			ois = new ObjectInputStream(socket.getInputStream());
			oos = new ObjectOutputStream(socket.getOutputStream());

			while (true) {
				ClientVo cv = (ClientVo) ois.readObject();
				int where = isr.read();
				if (where == 1) {
					now = cd.checkLogin(cv);
					oos.writeObject(now);
					oos.flush();
					if (now != null) {
						break;
					}
				} else if (where == 2) {
					cd.insert(cv);
				} else if (where == 0) {
					break;
				}
			}

			while (true) {
				String msg = br.readLine();

				String nowpic = "";
				if (msg.equals("1")) {
					String title = "고슴도치";
					String contents = "네발은 짧고, 몸통은 통통하다";
					fileWrite(title, contents);

					nowpic = fileRead(title); 
				}

				else if (msg.equals("2")) {
					String title = "다람쥐";
					String contents = "다람쥐는 큐트";
					fileWrite(title, contents);

					nowpic = fileRead(title); 
				} else if (msg.equals("0")) {
					break;
				}
				
				ClientVo ss =cd.checkLogin(now);

				ClientVo a = cd.checkFile(ss, nowpic);
				
				if (a == null) {
					System.out.println("작동");
					String nowFile = ss.getDownfile();
					if(nowFile.length()>3) {
						nowpic = nowFile + "+" + nowpic;
						System.out.println("합친것" + nowpic);
						cd.update(now, nowpic);
					}else {
						cd.update(now, nowpic);
					}
				} else {
					System.out.println("중복이라 db등록x");
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				serverSocket.close();
				br.close();
				pw.close();
				isr.close();
				socket.close();
				ois.close();
				oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	public void fileWrite(String title, String content) {
		try {
			fw = new FileWriter(title + ".txt");
			fw.write(content);
			fw.flush();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String fileRead(String title) {
		String nowpic = "";
		try {
			fr = new FileReader(title + ".txt");

			int a;
			String content = "";

			while ((a = fr.read()) != -1) {
				content = content + (char) a;
			}
			System.out.println("클라이언트가 요청한 내용" + content);

			pw.println(content);
			pw.flush();
			// 1

			nowpic = br.readLine();
			System.out.println(nowpic);
			fr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowpic;
	}

}
package practice0503okㅇ;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class ClientDao {

	public ArrayList<ClientVo> select() throws Exception {
		Connection conn = DBcon.getConnection();
		String query = "SELECT * FROM client";
		PreparedStatement stmt = conn.prepareStatement(query);
		ResultSet rs = stmt.executeQuery();

		ArrayList<ClientVo> ar = new ArrayList<>();
		while (rs.next()) {
			int num = rs.getInt(1);
			String name = rs.getString(2);
			String id = rs.getString(3);
			String pw = rs.getString(4);
			String downfile = rs.getString(5);
			ClientVo c = new ClientVo(num, name, id, pw,downfile);
			ar.add(c);
		}

		return ar;
	}

	public ClientVo checkLogin(ClientVo cv) throws Exception {
		ArrayList<ClientVo> ar = select();
		for (ClientVo a : ar) {
			if (a.getId().equals(cv.getId()) && a.getPw().equals(cv.getPw())) {
				return a;
			}
		}
		return null;
	}
	
	public ClientVo checkFile(ClientVo ss, String nowpic) throws Exception {
		ArrayList<ClientVo> ar = select();
		for (ClientVo a : ar) {
			if (a.getId().equals(ss.getId()) && a.getDownfile().contains(nowpic)) {
				return a;
			}
		}
		return null;
	}

	public void insert(ClientVo cv) throws Exception {
		Connection conn = DBcon.getConnection();
		String query = "INSERT INTO client (name,id,pw) VALUES (?,?,?)";
		PreparedStatement stmt = conn.prepareStatement(query);
		stmt.setString(1, cv.getName());
		stmt.setString(2, cv.getId());
		stmt.setString(3, cv.getPw());

		stmt.executeUpdate();
	}

	public void update(ClientVo now, String nowpic) throws Exception {
		Connection conn = DBcon.getConnection();
		String query = "UPDATE client SET downfile=? where num=?";
		PreparedStatement stmt = conn.prepareStatement(query);
		stmt.setString(1, nowpic);
		stmt.setInt(2, now.getNum());
		stmt.executeUpdate();
	}
	
	
	
	
	
	
}
package practice0503okㅇ;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBcon {
	public static Connection getConnection() throws Exception{
		String driver = "org.mariadb.jdbc.Driver";
		String url = "jdbc:mariadb://localhost:3306/savedown";
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url,"root","1234");
		return conn;
	}
}
package practice0503okㅇ;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ClientVo implements Serializable{
	private int num;
	private String name;
	private String id;
	private String pw;
	private String downfile;
}