본문 바로가기
IT/JAVA

자바 서버 소켓 멀티 쓰레드

by 최고영회 2013. 12. 21.
728x90
반응형
SMALL

public class SVSocket {

 

    /** 통신 포트*/
    private static final int PORT = 9999

    private Thread thread = null;
    private ServerSocket svrSocket = null;
   

    public SVSocket() {
     
        try {

            this.svrSocket = new ServerSocket(PORT);

            if (this.svrSocket != null) {
                this.thread = new ServerSocketThread(this.svrSocket);
                this.thread.start();
                
               System.out.println("  ----------------  @ 리스너 실행 @  ----------------");

            }

        } catch(IOException e) {
            System.out.println("  ----------------  $ CONNECTION ERROR $   ----------------");
        }
    }

 

    public void serverSocketClose() {
        if (this.thread != null) {
            this.thread.destroy();
            this.thread = null;
        }
    }
}

 

/**
 * 서버 소켓 클라이언트 소켓 대기 accept()
 * @author Administrator
 *
 */

class ServerSocketThread extends Thread {
    private ServerSocket svrSocket = null;
    private static Logger logger = Log.getLogger(ServerSocketThread.class);
 
    public ServerSocketThread() {
    }

    public ServerSocketThread(ServerSocket svrSocket) {
        this.svrSocket = svrSocket;
    }

    public void run() {

        try {
         
            while(true) {
                if (this.svrSocket != null) {
                    Socket socket = this.svrSocket.accept();
                    
                    if (socket != null) {
                        System.out.println("IP : " + socket.getInetAddress().getHostAddress() );
                        new ClientSocketThread(socket).start();
                    }
                }
            }


        } catch(IOException e) {
            System.out.println(e);
        }
    }
}


/**
 * 
 * 모든 데이터의 마지막에는 0x00으로 마지막을 처리하며
 * 앞자리 6자리는 실데이터의 size(length)이며 이 길이는 0x00(NULL)값을 포함한다.
 * 
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import org.apache.log4j.Logger;

 

public class ClientSocketThread extends Thread {
 
 private static Logger logger = Log.getLogger(ClientSocketThread.class);
 
 private Socket socket = null;
    private DataInputStream dis = null;
    private DataOutputStream  dos = null;
    
 public ClientSocketThread() {
 }
 
    public ClientSocketThread(Socket socket) {
        try {
            this.socket = socket;
            this.dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            this.dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
           
        } catch (IOException e) {
            System.out.println(e);
            this.closeSocket();
        }

        if (this.socket == null) {
            System.out.println("# Socket == null" );
            this.closeSocket();
        }
    }
   

    /**
     * 읽는 메소드 쓰레드 처리
     *
     */
    public void run() {
     
        int c = 0;
        int i = 0;
        String sLen = "";
        byte[] bReceive = null;
        
        try {
   
            while ((c = this.dis.read()) > 0) {
          
                if (i < 6) {
                    sLen += (char) c;
                }
    
                if (i == 6) {
                    bReceive = new byte[Integer.parseInt(sLen)];
                }
    
                if (i > 5) {
                    bReceive[i-6] = (byte)c;
                }
    
                if (Integer.parseInt(sLen) +5 == i ) {
                    break;
                }
    
                i++;
           }   
         

        } catch (IOException e) {
   
            System.out.println("$ READ [ERR]  IOException");
   
            e.printStackTrace();
        } 
  
        String receiveData = sLen + new String(bReceive);
  
 
        System.out.println("-- READ DATA STR --");
        System.out.println(receiveData);
        System.out.println("-- READ DATA END --");
   
        this.logic(receiveData);
    }
   
    /**
     * 전송
     * @param byteSend
     */

    public void logic(String data) {
     
       
 // 로직 구현 Factory Class (동적 클래스 생성)

        FunctionFactory functionFactory = new FunctionFactory(data);
        String sendData= functionFactory.getSendData();
        // 클라이언트 전송 처리
        this.send(sendData.getBytes());

        // 윗 부분은 개발 로직에 맞게 처리하면 된다.

        // ECHO 방식으로 했을 때는

        this.send(data.getBytes());
   }
    
    /**
     * 클라이언트에게 전송
     * @param b
     */
    public void send(byte[] b) {
        try {
      

            System.out.println("-- SEND DATA STR --");
            System.out.println("  "+new String(b));
            System.out.println("-- SEND DATA END --");

      
            if (this.dos != null) {
                this.dos.write(b);
                this.dos.flush();
                this.dos.close();
            } 
      
        } catch (IOException e) {
   
            System.out.println("$ SEND [ERR]  IOException" + e);
            e.printStackTrace();
        }
    }
    
    /**
     * 클라이언트 소켓 종료
     */
    public void closeSocket() {
        try {
            this.dis.close();
            this.dos.close();

            if (this.socket != null) {
                this.socket.close();
            }
        } catch (IOException e) {
        } catch (NullPointerException e) {
        }
    }
}

728x90
반응형
LIST

'IT > JAVA' 카테고리의 다른 글

NIO 이용 파일 카피  (0) 2013.12.21
Java 로 mail 보내기  (0) 2013.12.21
EJB  (0) 2013.12.21
file download 시 stream  (0) 2013.12.21
한글이름 file 저장 (unix 에서)  (0) 2013.12.21