본문으로 바로가기

자바 echo client / server 만들기

: 자바 Socket 통신을 이용해서 echo 서버/클라이언트를 만들어보겠습니다.


<EchoClient.java> : 클라이언트


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
 
public class EchoClient {
    public static void main(String[] args) throws Exception {
 
        Socket socket = new Socket("localhost"11111);
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        BufferedReader networkIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("클라이언트 입장");
 
        while (true) {
            System.out.print("입력하세요:");
            String theLine = userIn.readLine();
            out.println(theLine);
            out.flush();
            if (theLine.equalsIgnoreCase("Quit"))
                break;
            System.out.println("서버에서 보냄:[ " + networkIn.readLine() + " ]");
        }
        System.out.println("클라이언트 종료..");
        networkIn.close();
        out.close();
        socket.close();
    }
}
 
cs


<EchoClient.java> : 서버


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class EchoServer {
 
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(11111);
                Socket socket = serverSocket.accept();
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
 
            System.out.println("서버 대기중....");
            while (true) {
                String msg = br.readLine();
                if (msg.equalsIgnoreCase("Quit"))
                    break;
                System.out.println("클라이언트에서 보냄:[ " + msg + " ]");
                out.println(msg);
                out.flush();
            }
            System.out.println("서버종료..");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
cs



주의할점!

PrintWriter의 경우 println과 write가 있는데

println을 할때는 개행문자 "\n"가 필요없지만 write일 경우에는 "\n" 을 해줘야지 Output이 된다.