추상클래스. 특정 클래스 안에서 불려진 후 소캣 연결을 맺고 파일, 문자 입출력을 맡음.

이같은 방식으로 코드를 절약.

메소드 두 개(sendMsg, receiveMsg)는 필요에 따라(문자나 파일을 보내고 받는 등) 오버라이드해야 함.




package mp3example;


import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.net.Socket;

public abstract class ClientAgent {

private String ip;

private int port;

protected Socket socket;

protected DataInputStream din;

protected DataOutputStream dos;

public ClientAgent(String ip, int port) {

super();

this.ip = ip;

this.port = port;

}

public final void doExecute()throws Exception{

try{

connect();

sendMsg();

receiveMsg();

}finally{

closeAll();

}

}

private void connect() throws Exception{

this.socket = new Socket(this.ip, this.port);

this.din = new DataInputStream(this.socket.getInputStream());

this.dos = new DataOutputStream(this.socket.getOutputStream());

}

protected abstract void sendMsg()throws Exception;

protected abstract void receiveMsg()throws Exception;

private void closeAll() {

if(this.din != null){

try{ din.close(); }catch(Exception e){}

}

if(this.dos != null){

try{ dos.close(); }catch(Exception e){}

}

if(this.socket != null){

try{ this.socket.close(); }catch(Exception e){}

}

}

}

Posted by 타다키치
,