본문 바로가기

JAVA/DAY 22 _ 23.09.15

Thread활용_ChattingRoom_serverMain

1. ServerRecieveThread class

class ServerRecieveThread extends Thread{
	
	private String nickName;
	private Socket socket;

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

	@Override
	public void run() {
		
		try {
			
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			
			while(true) {
				int command = dis.readInt();
				
				// 1. 닉네임 설정 / 2. 메세지보내기 / 3. 종료
				if(command == 1) {
					nickName = dis.readUTF();
					ClientDto clientDto = new ClientDto(nickName, socket);
					
					BroadCaster.list.add(clientDto);
					
					BroadCaster.broadCast(nickName + "님이 입장하셨습니다");

				}
				else if(command == 2) {
					String message = dis.readUTF();
					BroadCaster.broadCast(nickName + " ] " +   message);
					
				}
				else if(command == 3) {
					for(ClientDto clientDto : BroadCaster.list) {
						
						// 동명이인이 가능하니까 주소값으로 비교하는게 맞지
						if(clientDto.getSocket() == socket) {
							BroadCaster.list.remove(clientDto);	
							break;
						}
					}
					
					BroadCaster.broadCast(nickName + "님이 퇴장하셨습니다");
					socket.close();
					break;
					
				}
	
			}

		}catch (Exception e) {
			// e.printStackTrace();
			
			for(ClientDto clientDto : BroadCaster.list) {
				
				// 동명이인이 가능하니까 주소값으로 비교하는게 맞지
				if(clientDto.getSocket() == socket) {
					BroadCaster.list.remove(clientDto);	
					BroadCaster.broadCast(nickName + "님의 연결이 끊겼습니다");
				}
			}
		
		}

	}

}

 

2. BroadCaster class

// ~~님이 입장하셨습니다 --> 방송해주는 클래스
class BroadCaster{
	
	public static List<ClientDto> list = new Vector<>();
	
	public static void broadCast(String message) {
		
		System.out.println("서버 테스트 : " + message);
		
		for(ClientDto clientDto : list) {
			
			try {
				DataOutputStream dos =
					new DataOutputStream(clientDto.getSocket().getOutputStream());
				dos.writeUTF(message);
	
			}catch (Exception e) {
				// e.printStackTrace();
				
				
			}
	
		}

	}

}

 

3.  ClientDto

class ClientDto{
	
	private String nickName;
	private Socket socket;
	
	public ClientDto(String nickName, Socket socket) {
		this.nickName = nickName;
		this.socket = socket;
	}

	
	public String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}
}

 

4. Main

public static void main(String[] args) {

    System.out.println("[서버] 가동 시작 ... ");
    try (ServerSocket serverSocket = new ServerSocket(8888)){

        while(true) {
            Socket socket = serverSocket.accept();
            new ServerRecieveThread(socket).start();

        }



    }catch (Exception e) {
        e.printStackTrace();
    }

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

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