2013년 9월 2일 월요일

(자바 멀티쓰레드 클라이언트 서버 네트워크)Multi-Thread Echo Client, Server

(자바 멀티쓰레드 클라이언트 서버 네트워크)Multi-Thread Echo Client, Server

이전 예제인 EchoServer의 경우 동시에 여러 개의 클라이언트를 처리하는데 있어서는 read 메소드의 Blocking으로 인해 어려움이 있다.
즉 동시에 여러 클라이언트의 요구를 처리 하지 못한다.
이문제를 해결하기 위해 다중 스레딩(Multi-Threading)을 구현한 서버를 사용하는 것이다.
다중 스레드 서버는 클라이언트가 접속 할때 마다 1개 이상의 스레드를 만들어 돌리기 때문에 블록킹 I/O 문제를 해결해 준다.
즉 메인 스레드는 클라이언트의 연결을 받기만 하고 클라이언트와 데이터를 주고 받는 일은 별도의 Thread에서 처리 하도록 구성한다.


//여러개의 클라이언트를 처리하기 위해 
//멀티스레드로 구현한 MultiThreadEchoServer
import java.io.*;
import java.net.*;
class MultiThreadEchoServer extends Thread {  
protected Socket sock;
//----------------------- Constructor
MultiThreadEchoServer (Socket sock) { this.sock = sock;}

//------------------------------------
public void run() {
try   {                
                System.out.println(sock + ": 연결됨");
               InputStream fromClient = sock.getInputStream();
                OutputStream toClient = sock.getOutputStream();
                byte[] buf = new byte[1024];         int count;
                while( (count = fromClient.read(buf)) != -1 ) {
                    toClient.write( buf, 0, count );
        System.out.write(buf, 0, count);
   }
                toClient.close();
                System.out.println(sock + ": 연결 종료");

catch( IOException ex )   {
System.out.println(sock + ": 연결 종료 (" + ex + ")");



                finally {
try   {
if ( sock != null )  sock.close();

catch( IOException ex ) {}
}        
}

//------------------------------------
public static void main( String[] args )   throws IOException    {
        ServerSocket serverSock = new ServerSocket( Integer.parseInt(args[0]) );
        System.out.println(serverSock + ": 서버 소켓 생성");



        while(true)        {
Socket client = serverSock.accept();
MultiThreadEchoServer myServer = new MultiThreadEchoServer(client);
myServer.start();
        }
    }
}



댓글 없음:

댓글 쓰기