보뇨 다이어리

서버와 클라이언트 통신 본문

카테고리 없음

서버와 클라이언트 통신

보뇨 2018. 2. 18. 22:51
반응형
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
import java.net.*;
import java.io.*;
 
public class EchoServer {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(10001);
            System.out.println("Waiting connect..");
            
            Socket sock = server.accept();
            
            InetAddress inetaddr = sock.getInetAddress();
            System.out.println(inetaddr.getHostAddress() + " 로 부터 접속했습니다");
            
            OutputStream out = sock.getOutputStream();
            InputStream in = sock.getInputStream();
            
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            
            String line = null;
            
            while((line = br.readLine()) != null) {
                System.out.println("클라이언트로부터 전송받은 문자열 = " + line);
                pw.println(line);
                pw.flush();
            }
            
            pw.close();
            br.close();
            sock.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}
cs


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
import java.net.*;
import java.io.*;
 
public class EchoClient {
    public static void main(String[] args) {
        try {
            Socket sock = new Socket("127.0.0.1"10001);
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            
            OutputStream out = sock.getOutputStream();
            InputStream in = sock.getInputStream();
            
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            
            String line = null;
            
            while((line = keyboard.readLine()) != null) {
                if(line.equals("quit")) break;
                
                pw.println(line);
                pw.flush();
                
                String echo = br.readLine();
                System.out.println("서버로부터 전달받은 문자열 = " + echo);
            }
            
            pw.close();
            br.close();
            sock.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
cs



출처 http://blog.naver.com/PostView.nhn?blogId=cyberhole&logNo=110133796577&parentCategoryNo=&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView

반응형