nodejs8- 자바클라이언트 채팅 베이직/java client chat basic(3)

👉🏻 코드설명 / Code Explanation

✔️ ChatClientGUI.java

— ChatClientGUI 생성자 / ChatClientGUI Constructor

1)채팅표시 영역 / Chat display area

      chatArea = new JTextArea();
      chatArea.setEditable(false);
      JScrollPane scrollPane = new JScrollPane(chatArea);
      add(scrollPane, BorderLayout.CENTER);

1-1)채팅표시 영역으로 수정할 수 없도록 setEditable(false로 설정되어 있습니다.)
It is set to setEditable(false) to prevent editing within the chat display area.

1-2)대화내용이 많을 경우 스크롤을 적용합니다.
Scroll functionality is applied if the conversation content is extensive.

JScrollPane scrollPane = new JScrollPane(chatArea);

1-3)채팅표시 영역을 가운데 가득 채우도록 배치합니다.
Position the chat display area to fully fill the center.

add(scrollPane, BorderLayout.CENTER);

1-4)레이아웃은 다음과 같습니다.
The layout is as follows.

+-----------------------------------+

|             NORTH (북)            |
+-------+-------------------+-------+

|  WEST |                   |  EAST |
|  (서) |    CENTER (중앙)   |  (동) |
|       |                   |       |
+-------+-------------------+-------+

|             SOUTH (남)            |
+-----------------------------------+

2)채팅 입력창 및 send 버튼
Chat input field and Send button

2-1)채팅을 입력 창과 send버튼을 정의 하고 배치합니다.
Define and position the chat input field and the send button.

        JPanel inputPanel = new JPanel(new BorderLayout());
        messageInput = new JTextField();
        sendButton = new JButton("보내기/send");
        sendButton.addActionListener(this);

        inputPanel.add(messageInput, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);

2-2)메시지 입력창과 보내기 버튼을 한 세트로 묶기 위한 도구입니다.
This is a tool for grouping the message input field and the send button together as a single unit.

JPanel inputPanel = new JPanel(new BorderLayout());

2-3)버튼과 이벤트를 연결합니다
Connect the button to the event.

sendButton.addActionListener(this);

2-4)this자기 자신의 클래스(ChatClientGUI)를 참조합니다.
It references its own class (ChatClientGUI).

2-5)이때 이 클래스에 선언된 actionPerformed(ActionEvent e) 이 함수를 호출합니다.
At this point, the actionPerformed(ActionEvent e) function declared in this class is called.

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sendButton) {
            String message = messageInput.getText();
            if (!message.isEmpty()) {
                out.println(message); // 서버로 메시지 전송 / Send message to server
                chatArea.append("나Me: " + message + "\n");
                messageInput.setText("");
            }
        }
    }

2-5)actionPerformed(ActionEvent e)함수앞에 @Override 어노테이션이 붙어있어서 재정의한 함수임을 알 수 있습니다.
The @Override annotation preceding the actionPerformed(ActionEvent e) function indicates that it is an overridden function.


3)텍스트 입력창과버튼을 패널에 붙이고 아래쪽(south)에 배치합니다.
Attach the text input field and the button to the panel and position them at the bottom (south).

        inputPanel.add(messageInput, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);

4)nodejs서버에 접속하고 메세지 수신스레드를 시작합니다.
Connect to the Node.js server and start the message reception thread.

connectToServer();

4-1)connectToServer함수
connectToServer function

    private void connectToServer() {
        try {
            socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            chatArea.append("서버에 연결되었습니다.\nsercer connected");

            // 서버로부터 메시지를 수신하는 스레드 시작
            // Start a thread to receive messages from the server
            Thread receiveThread = new Thread(this::receiveMessages);
            receiveThread.start();

        } catch (IOException e) {
            chatArea.append("서버 연결에 실패했습니다: " + e.getMessage() + "\n");
        }
    }

— 나머지 함수 / Remainder function

1)서버로부터 메세지 받기
Receive message from server

    private void receiveMessages() {
        String message;
        try {
            while ((message = in.readLine()) != null) {
                chatArea.append("서버server: " + message + "\n");
            }
        } catch (IOException e) {
            chatArea.append("서버 연결이 끊어졌습니다.\nFailed to connect to server.");
        } finally {
            closeConnection();
        }
    }

1-1)무한루프 하면서 메세지를 읽어와서 채팅영역에 표시합니다.
It runs an infinite loop to read messages and display them in the chat area.

            while ((message = in.readLine()) != null) {
                chatArea.append("서버server: " + message + "\n");
            }

2)서버와 접속 종료 처리부분입니다.
This section handles the disconnection from the server.

    private void closeConnection() {
        try {
            if (out != null) out.close();
            if (in != null) in.close();
            if (socket != null && !socket.isClosed()) socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3)main함수로 프로그램의 첫 진입점입니다.
The main function serves as the program’s initial entry point.

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ChatClientGUI::new);
    }

3-1)오류 발생할 수 있는 메인스레드 대신에 invokeLater라는 GUI전용스레드로 실행하도록 합니다.
Instead of the main thread, where errors might occur, execute the task using a GUI-specific thread called invokeLater.

Leave a Reply