Echo 서버는 메아리처럼 client에서 메시지를 서버에 전송하여
서버가 받은 메시지를 그대로 client에 전송하는 프로그램이다.
서버
package chap12.exam03.echo; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws Exception { // 1. Server Socket 생성 ServerSocket server = new ServerSocket(); // 2. IP 개방 (localhost는 자기만 들어오고, 자신의 ip를 입력하면 외부에서 접속가능) server.bind(new InetSocketAddress("여기에 IP를 입력해야 정상적으로 동작해요", 5001)); // 3. 요청 대기 while(true) { System.out.println("Connect Ready"); Socket socket = server.accept(); // block // 접속 요청이 있을 경우 요청 주소를 뽑아 낸다.(선택) InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress(); System.out.println("접속 완료 : " + addr.getAddress()); // 4. InputStream으로 보내온 메시지를 받는다. InputStream is = socket.getInputStream(); // 핵심 BufferedInputStream bis = new BufferedInputStream(is); InputStreamReader reader = new InputStreamReader(bis); // 5. 출력 char[]arr = new char[100]; reader.read(arr); // ㅁㅁㅁ는 \0이고 배열의 공백을 의미한다, 38번째 줄의 replace를 생략한다면 이상한 문자를 볼 수 있다. String msg = new String(arr).replace('\0', ' '); System.out.println("[client] " + msg); // 6. OutputStream으로 보내온 메시지를 전송한다. OutputStream os = socket.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(os); OutputStreamWriter writer = new OutputStreamWriter(bos, "UTF-8"); writer.write(msg); writer.flush(); // 서버는 켜져있어야 하므로 자원반납을 생략 } } }
클라이언트
package chap12.exam03.echo; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { // 1. 소켓 생성 Socket socket = new Socket(); // 2. 접속 요청 try { socket.connect(new InetSocketAddress("여기에 IP를 입력해야 정상적으로 동작해요", 5001)); System.out.println("접속 완료"); OutputStream os = socket.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(os); OutputStreamWriter writer = new OutputStreamWriter(bos, "UTF-8"); writer.write("Hello, Server"); writer.flush(); // 3. 데이터 전송 // 4. 받아온 데이터 출력 InputStream is = socket.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); InputStreamReader reader = new InputStreamReader(bis); char[] arr = new char[100]; reader.read(arr); String msg = new String(arr); System.out.println("내가 받은 메세지 : " + msg); // 5. 자원반납 os.close(); bos.close(); writer.close(); is.close(); bis.close(); reader.close(); } catch (Exception e) { // } } }
서버의 19번째 줄과 클라이언트의 20번째 줄에
접속할 대상의 IP를 입력해주어야 하고 1개의 컴퓨터로 테스트 할 경우
대상 Server가 자기 자신이므로 자신의 IP를 입력하면 된다.
그리고 서버는 이클립스에서 실행하고
클라이언트를 따로 실행해야 하는데
https://qdgbjsdnb.tistory.com/79 를 참조하여 cmd에서 클라이언트를 작동해보자.
'개념 및 코딩 > 10.네트워크' 카테고리의 다른 글
[JAVA]10-06.UDP, Datagram (0) | 2018.09.27 |
---|---|
[JAVA]10-05.N:M MultiChat Server, Client (2) | 2018.09.27 |
[JAVA]10-04.1:1 Chat Server, Client (0) | 2018.09.27 |
[JAVA]10-02.TCP Server, Client (0) | 2018.09.27 |
[JAVA]10-01.Java Network 기초, IP 얻는법 (0) | 2018.09.27 |