본문 바로가기

JAVA/DAY 22 _ 23.09.15

Thread활용_ChattingRoom_clientMain

1. recieveThread class

class RecieveThread extends Thread{
	
	private Socket socket;
	

	public RecieveThread(Socket socket) {
		this.socket = socket;
	}


	public void run() {
		
		try {
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			
			while(true) {
				String message = dis.readUTF();
				System.out.println(message);
			}
			
		}catch (Exception e) {
			//e.printStackTrace();
			System.out.println("접속이 종료되었습니다");
			
		}
	}
}

 

2. SendThread class

class SendThread extends Thread{
	
	private Scanner scn;
	private Socket socket;
	 

	public SendThread() {}

	public SendThread(Scanner scn, Socket socket) {
		this.scn = scn;
		this.socket = socket;
	}



	public void run() {
		
		try{
			DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
			
			while(true) {
				System.out.println("보낼 메세지 (종료 = q) > ");
				String message = scn.nextLine();
				
				if(message.equals("q")) {
					dos.write(3);
					System.out.println("[클라이언트] 프로그램 종료");
					socket.close();
					break;
				}
				
				dos.write(2);
				dos.writeUTF(message);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}

	}

}

 

3. Main

public class _1ClientMain {

	public static void main(String[] args) {
		
		Scanner scn = new Scanner(System.in);
		
		System.out.println("[클라이언트] 시작");
		System.out.println("[클라이언트] 서버 접속 중...");
		
		
		try{
			Socket socket = new Socket("localhost", 8888);
			System.out.println("[클라이언트] 서버 접속 성공");
			System.out.println("[클라이언트] 사용할 닉네임을 입력하세요");
			System.out.print("[클라이언트] 닉네임 > ");
			String nickName = scn.nextLine();
			
			DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
			
			dos.write(1);
			dos.writeUTF(nickName);
			
			new SendThread(scn, socket).start();
			new RecieveThread(socket).start();
		
		}catch (Exception e) {
			e.printStackTrace();
		}

	}

}

'JAVA > DAY 22 _ 23.09.15' 카테고리의 다른 글

네트워크 관련 이론  (0) 2023.09.15
Thread활용_ChattingRoom_serverMain  (0) 2023.09.15