본문 바로가기

Java SE/Socket 03

Socket 03

클라이언트와 서버가 서로 요청/응답을 계속해서 수행하는 내용으로 변경함

클라이언트 측

import java.net.*;
import java.io.*;

class  GuguClient {
 public static void main(String[] args) throws Exception {

  Socket soc = new Socket("localhost", 1234);

  PrintWriter pw = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
  //BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
  BufferedInputStream bin = new BufferedInputStream(soc.getInputStream());
  BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
 
  while(true) {
   System.out.print("서버로 전송할 숫자를 입력해 주세요 ");
   String dan = keyboard.readLine();

   pw.println(dan);
   pw.flush();

   String line = null;
   int count = 0;
   while((count=bin.available())==0);
   byte[] buf = new byte[count];
   int read = bin.read(buf, 0, buf.length);
   
   System.out.println(new String(buf, 0, read));
  }
 }
}


서버측

import java.net.*;
import java.io.*;

class  GuguServer {
 public static void main(String[] args) throws Exception {

  ServerSocket ss = new ServerSocket(1234);
  System.out.println("서버 실행중....");

  Socket soc = ss.accept();

  BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
  PrintWriter pw = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
 
  String line = null;
  try{
   while((line=br.readLine())!= null) {
     int dan = Integer.parseInt(line);

     String str = "";
     for(int i=1;i<=9;i++) {
      str += dan + " x " + i + " = " + (dan*i) + "\n";
     }

     pw.println(str);
     pw.flush();
   }
  }catch(Exception soce){
   System.err.println("클라이언트 나감");
  }

  System.out.println("서버 종료됨");
 }
}