■ 공부/JAVA

[JAVA] 소켓통신 : 학점 반환하기

J U N E 2024. 1. 30. 00:21

■ 서버용 

import java.io.*;
import java.util.*;
import java.net.*;

public class ServerC {

    private static class ScoreBoard {
        ArrayList<String[]> scoreList = new ArrayList<>();
        
        public void put(String key, String value) {
            boolean done = false;
            for (String[] score : scoreList) {
                if (score[0].compareToIgnoreCase(key) == 0) {
                    score[1] = value;
                    done = true;
                    break;
                }
            }
            if (!done)
                scoreList.add(new String[] {key, value});
        }
        
        public String get(String key) {
            for (String[] score : scoreList) {
                if (score[0].compareToIgnoreCase(key) == 0) {
                    return score[1];
                }
            }
            return null;
        }
    }
    
    public static void main(String[] args) throws IOException {
        ServerSocket listener = null;
        Socket socket = null;
        Scanner sc = new Scanner(System.in);
        BufferedReader in = null;
        BufferedWriter out = null;
        
        //HashMap<String, String> scores = new HashMap<>();
        ScoreBoard scores = new ScoreBoard();
        
        FileReader fr = new FileReader("C:\\Users\\june\\Desktop\\scores.txt");
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            String[] arr = line.split(" ");
            scores.put(arr[0], arr[1]);
        }
        br.close();
        fr.close();
/*
        List<String> keyList = new ArrayList<>(scores.keySet());
        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }
        });
        for (String name : keyList) {
            System.out.println(name + " " + scores.get(name));
        }
*/
       
        try {
            listener = new ServerSocket(8000);
            System.out.println("연결 대기 중...");
            socket = listener.accept();
            System.out.println("연결되었습니다.");

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            while (true) {
                String clientInput = in.readLine();
                if (clientInput.isEmpty()) continue;
                if (clientInput.equals("bye")) {
                    System.out.println("클라이언트 측에서 종료");
                    break;
                }
                String score = scores.get(clientInput);
                if (score == null) score = "해당학생 없음";
                System.out.println("클라이언트: " + clientInput);
                System.out.println("답장보내기 >> " + score);
//                String serverOutput = sc.nextLine();
//                out.write(serverOutput + "\n");
                out.write(score);
                out.newLine();
                out.flush();
            }

        }
        catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }
        finally {
            try {
                listener.close();
                socket.close();
                sc.close();
            }
            catch (IOException e) {
                System.out.println("통신 중 오류 발생");
            }
        }
    }
}

 

■ 클라이언트용

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

public class ClientB {
    public ClientB() {
    }
    
    public static void main(String[] args) {
        Socket socket = null;
        Scanner sc = new Scanner(System.in);
        BufferedReader in = null;
        BufferedWriter out = null;
        
        try {
            socket = new Socket("localhost", 8000);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            
            while(true) {
                System.out.print("서버로 보내기 >>> ");
                String clientOutput = sc.nextLine();
                if (clientOutput.equals("bye")) {
                    out.write(clientOutput);
                    out.newLine();
                    out.flush();
                    break;
                }
                
                out.write(clientOutput);
                out.newLine();
                out.flush();
                String serverInput = in.readLine();
                System.out.println("서버: " + serverInput);
            }
        } catch (IOException var15) {
            System.out.println(var15);
        } finally {
            try {
                sc.close();
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException var14) {
                System.out.println("서버 통신 중 오류");
            }
            
        }
        
    }
}

 

대소문자 무시하고 찾아주기 위해 Hashmap 대신 클래스를 하나 추가함.

 

'■ 공부 > JAVA' 카테고리의 다른 글

[JAVA] DragListener  (0) 2024.02.12
[JAVA] Graphics2D  (1) 2024.01.31
[JAVA] 소켓통신 : 채팅프로그램  (0) 2024.01.26
[JAVA] File 클래스 : cmd 구현하기  (0) 2024.01.25
[JAVA] MainFrame 소스  (0) 2024.01.24