Notice
Recent Posts
Recent Comments
:: ADVANCE ::
[Java] Echo server & client 본문
반응형
[참고] http://djeong.kunsan.ac.kr/teaching/08.02.fall.03.ComNet/Supplement-03-TCP%20Programming.pdf
Server
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import java.net.Socket; import java.net.ServerSocket; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; // import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.IOException; public class EchoServer { private ServerSocket server; public EchoServer(int port) throws IOException { server = new ServerSocket(port); } public void service() throws IOException { System.out.println("EchoServer is ready."); Socket client = server.accept(); InputStream is = client.getInputStream(); OutputStream os = client.getOutputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); PrintWriter out = new PrintWriter(os, true); while(true) { String msg = in.readLine(); System.out.println(msg); if(msg.equals("bye")) { break; } out.println(">> " + msg); } } public void close() throws IOException { server.close(); } public static void main(String args[]) { try { EchoServer es = new EchoServer(1111); es.service(); es.close(); } catch(Exception e) { e.printStackTrace(); } } } | cs |
Client
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; //import java.io.OutputStreamWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; public class EchoClient { private Socket socket; private EchoClient(String host, int port) throws Exception { socket = new Socket(host, port); } public void echo() throws IOException { OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); PrintWriter out = new PrintWriter(os, true); BufferedReader con = new BufferedReader(new InputStreamReader(System.in)); while(true) { String msg = con.readLine(); out.println(msg); if(msg.equals("bye")) break; System.out.println(in.readLine()); } } public void close() throws IOException { socket.close(); } public static void main(String args[]) { try { EchoClient ec; System.out.println("Enter a message\n"); if(args.length > 0) ec = new EchoClient(args[0], 1111); else ec = new EchoClient("localhost", 1111); ec.echo(); ec.close(); } catch(Exception e) { e.printStackTrace(); } } } | cs |
반응형
Comments