순수 자바로 로컬 서버에서 실행할 수 있는 채팅 프로그램을 구현하는 것을 목표로 했다.
연결하고 1대1 대화가 가능하도록 먼저 구현하고 차차 n:n 채팅이 되도록 리팩토링 해보자.
서버 코드
package chat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import static util.MyLogger.log;
public class Server {
private static final int PORT = 13423;
public static void main(String[] args) throws IOException {
log("서버 시작");
ServerSocket serverSocket = new ServerSocket(PORT);
log("Listening to " + PORT + " Port ...");
log("클라이언트의 연결을 기다리고 있습니다...");
Socket socket = serverSocket.accept(); // 연결은 OS가 해주되, 자바로 불러오는 것을 accept 메서드로 소켓을 설정
log("클라이언트 연결 됨 - 클라이언트 정보 : " + socket);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
while (true) {
// 클라이언트로부터 문자 받기
String received = input.readUTF();
System.out.println(socket.getInetAddress() + " : " + received);
if (received.equals("exit")) {
break;
}
// 클라이언트에게 문자 보내기
System.out.print("[관리자] : ");
String toSend = sc.nextLine();
output.writeUTF(toSend);
}
//자원정리 추후 구현
input.close();
output.close();
socket.close();
}
}
클라이언트 코드
package chat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import static util.MyLogger.log;
public class Client {
private static final int PORT = 13423;
public static void main(String[] args) throws IOException {
log("클라이언트 시작");
Socket socket = new Socket("localhost", PORT);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
log("소켓 연결 : " + socket);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("[나] : "); // 닉넴으로 수정해야함 -> 닉넴 변수가 필요
String toSend = sc.nextLine();
// 서버에 문자 보내기
output.writeUTF(toSend);
if (toSend.equals("exit")) {
break;
}
// 서버에서 부터 문자 받기
String received = input.readUTF();
System.out.println("[관리자] : " +received);
}
// 자원 정리 로직 추후 구현
input.close();
output.close();
socket.close();
}
}
'Java > Java' 카테고리의 다른 글
[Java] 까먹지 말아야 할 Java 스레드 생명 주기 및 상태 전이 (0) | 2025.03.08 |
---|---|
[Java] 까먹지 말아야 할 Java 메모리 구조 (1) | 2025.03.04 |
[Java] 두줄로 이해하는 객체 직렬화, 역직렬화 (1) | 2025.01.28 |
[Java] 예외처리 - 부모 자식 관계 (1) | 2025.01.02 |
[Java] 제네릭 (Generic) (2) (1) | 2024.10.10 |