본문 바로가기

Java SE/Socket 05

Socket 05

클라이언트 측의 코드를 수정하여 송/수신 기능을 하는 각 메소드를 선언하고 쓰레드 2개를 적용하여 병행처리하도록 수정함

클라이언트측 코드

import java.net.*;
import java.io.*;
/* 서버측으로 데이터를 전송하는 부분과 수신하는 부분을 쓰레드로 분리하여 병행처리하도록 수정함*/
class  ChatClient {

 static PrintWriter pw;
 static BufferedInputStream bin;
 static BufferedReader keyboard;

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

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

  pw = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
  bin = new BufferedInputStream(soc.getInputStream());
  keyboard = new BufferedReader(new InputStreamReader(System.in));
 
  new SendThread().start(); // 키보드로부터 입력을 받아서 서버에 전송한다
  new ReceiveThread().start(); // 서버에서 데이터를 수신하여 모니터에 출력한다.
 }

 /* 송신기능 메소드*/
 private static void send() {
  String dan = null;
  while(true) {
   System.out.print("서버로 전송할 숫자를 입력해 주세요 ");
   try{
    dan = keyboard.readLine();
    pw.println(dan);
    pw.flush();
    Thread.sleep(20);
   }catch(Exception e){e.printStackTrace();}
  }
 }
 
 /* 수신기능 메소드*/
 private static void receive() {
  int count = 0;
  byte[] buf = null;
  int read = 0;

  while(true) {
   try{
    Thread.sleep(20);
    count = bin.available();
    if(count==0) continue;
    buf = new byte[count];
    read=bin.read(buf, 0, buf.length);
    System.out.println();
    System.out.println(new String(buf, 0, read));
   }catch(Exception e){e.printStackTrace();}
  }
 }

 /* 내부 클래스로 선언한 송신 쓰레드*/
 static class SendThread extends Thread  {
  public void run() {
   ChatClient.send();
  }
 }

 /* 내부 클래스로 선언한 수신 쓰레드*/
 static class ReceiveThread extends Thread  {
  public void run() {
   ChatClient.receive();
  }
 }
}


서버측 코드 (변경없음)

import java.net.*;
import java.io.*;
/* 클라이언트가 종료되면 서버는 계속 다른 클라이언트를 대기하는 상태로 전환되도록 한다*/
class  ChatServer {
 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("클라이언트 나감");
   }
  } // 바깥 while()
 }
}