상세 컨텐츠

본문 제목

Java - ServerSocket, Thread를 적용한 에코메시지 테스트

개발/Java

by 뉴에이스 2018. 10. 4. 14:07

본문

	서버 프로그램 작성
	HTTP - TCP(ServerSocket, Socket)
	
	ServerSocket - 서버
	Socket - 클라이언트

 

서버 소스

 

class EchoThread extends Thread {
	private Socket s;
	EchoThread(Socket s) {
		this.s = s;
	}
	public void run() {
		try {
			// 접속한 클라이언트가 보내준 메세지 읽기
			DataInputStream dis = new DataInputStream(s.getInputStream());
			// 접속한 클라이언트에게 메세지 전송하기
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			while  (true) {
				String msg = dis.readUTF();
				if (msg.equals("quit")) break;
				
				dos.writeUTF(msg);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

public static void main(String[] args) {
	try {
		ServerSocket server = new ServerSocket(10001);
		while (true) {
			Socket s = server.accept();
			System.out.println("클라이언트 접속");

			// 스레드 방식으로 변경
			EchoThread et = new EchoThread(s);
			et.start();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}

 

서버 결과

 

클라이언트 접속 // 클라이언트 접속 후 출력

 

클라이언트 소스

 

public static void main(String[] args) {
	try {
		Socket socket = new Socket("localhost", 10001);
		Scanner scanner = new Scanner(System.in);

		DataInputStream dis = new DataInputStream(socket.getInputStream());
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		while(true) {
			System.out.println("전송 메시지(종료 : quit) : ");
			String msg = scanner.nextLine();
			dos.writeUTF(msg);
			
			if(msg.equals("quit")) break;
			
			String recvMsg = dis.readUTF();
			System.out.println("에코메시지 : " + recvMsg);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}

 

클라이언트 결과

 

전송 메시지(종료 : quit) : 
test msg // 입력한 메시지
에코메시지 : test msg
전송 메시지(종료 : quit) : 
quit // 입력한 메시지

관련글 더보기

댓글 영역