Creating a simple echo client

2023. 2. 14. 17:55자바

SimpleEchoClient class를 선언하며 시작합니다.

 

메인 메서드에서는 다음과 같이 애플리케이션 시작 메시지가 표현됩니다.

 

public class SimpleEchoClient {
    public static void main(String args[]) {
        System.out.println("Simple Echo Client");
 ...
    }
}

서버에 연결하려면 Socket 인스턴스를 만들어야합니다.

다음 예시에서는 서버와 클라이언트가 동일한 컴퓨터에서 실행중입니다.

InetAddress 클래스의 static getLocalHost 메서드는 주소를 리턴하고,

port 6000과 함께 Socket class의 생성자에서 사용됩니다.

 

서버와 클라이언트가 서로 다른 컴퓨터에 위치한 경우엔,

localAddress가 아닌 서버의 주소를 사용합니다.

 

try {
        System.out.println("Waiting for connection.....");
        InetAddress localAddress = InetAddress.getLocalHost();
        
        try (
                Socket clientSocket = new Socket(localAddress, 6000);
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
        ) {
        ...
        }
} catch (IOException ex) {
        // Handle exceptions
        }

 

그 후 사용자에게 텍스트를 입력하라는 의미의 Enter text 메시지가 표시됩니다.

 

만약 텍스트가 quit라면, 무한 루프가 종료되며, 애플리케이션이 종료됩니다.

그렇지않으면, 텍스트는 out 객체를 사용하여 서버로 전송됩니다.

 

System.out.println("Connected to server");
Scanner scanner = new Scanner(System.in);
while (true) {
    System.out.print("Enter text: ");
    String inputLine = scanner.nextLine();
    if ("quit".equalsIgnoreCase(inputLine)) {
    break;
    }
    out.println(inputLine);
    String response = br.readLine();
    System.out.println("Server response: " + response);
}

 

프로그램은 두 개의 개별 프로젝트로 또는 단일 프로젝트 내에서 구현될 수 있습니다.

어느 쪽이든 먼저 서버를 시작한 다음 => 클라이언트를 시작해야합니다.

'자바' 카테고리의 다른 글

Creating a simple echo server  (0) 2023.02.14
The client/server architecture  (0) 2023.02.14
Using the URLConnection class withbuffers and channels  (0) 2023.02.14
Using the URLConnection class  (0) 2023.02.14
NIO support  (0) 2023.02.14