Java SE/Socket 04

Socket 04

Soul-Learner 2008. 4. 17. 15:19

서버측 코드만 약간 수정하여 클라이언트가 종료되어도 서버는 다른 클라이언트를 대기하는 상태로 넘어가도록 했다.

서버측 코드

import java.net.*;
import java.io.*;
/* 클라이언트가 종료되면 서버는 계속 다른 클라이언트를 대기하는 상태로 전환되도록 한다*/
class  GuguServer {
 public static void main(String[] args) throws Exception {

  ServerSocket ss = new ServerSocket(1234);
  System.out.println("서버 실행중....");
  while(true) {
   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("클라이언트 나감");
   }
  }
 }
}


클라이언트 측 코드 (변경없음)

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()));
  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));
  }
 }
}