Google AdSense


[Java][ftp4j] Socket 연결에 timeout 설정하기 by Sigel

ftp4j를 아무 생각 없이 사용하고 있었다. 분명 개발하던 컴퓨터에서는 FTP의 Socket timeout이 20초 정도였는데 리눅스 서버로 옮기니 이 녀석이 180초나 되는 것이다. -ㅅ-;;

ftp4j는 서버와 연결할 때 FTPConnector라는 것을 상속받아 구현한 connector를 사용한다. 접속 시 아무 connector도 설정하지 않으면 가장 기본적인 DirectConnector를 사용한다. 이 connector는 프록시나 인코딩 등을 사용하지 않고 바로 Socket을 직접 열어서 연결한다. (라이브러리와 함께 제공되는 connector는 요기의 "All Known Implementing Classes"를 참조)

헌데 이 DirectConnector 녀석의 timeout이 플랫폼이나 시스템 마음대로인 것이다. TㅅT 해결 방법은 아주 간단~~ DirectConnector 대신 사용할 녀석을 만들고 Socket을 열 때 timeout을 주면 여러 시스템에서도 같은 timeout을 가질 수 있다.

public class TimeoutDirectConnector implements FTPConnector
{
    private int timeout;

    public TimeoutDirectConnector(int timeout)
    {
        this.timeout = timeout;
    }

    private Socket connect(String host, int port) throws IOException
    {
        Socket result = new Socket();
        result.connect(new InetSocketAddress(host, port), this.timeout);
        return result;
    }

    @Override
    public Socket connectForCommunicationChannel(String host, int port) throws IOException
    {
        return connect(host, port);
    }

    @Override
    public Socket connectForDataTransferChannel(String host, int port) throws IOException
    {
        return connect(host, port);
    }
}

ft4j의 DirectConnector와 나머지 부분은 동일하고 Socket 객체 생성하는 부분에만 timeout을 줬다. 이러면 connector 생성 끝~~ 자.. FTPClient에 새로 만든 connector를 사용하도록 설정해주자.

long startTime = System.currentTimeMillis();
try
{
    FTPClient ftp = new FTPClient();
    ftp.setConnector(new TimeoutDirectConnector(3000));
    ftp.connect(HOST, PORT);
    ftp.login(USER, PASSWORD);
}
catch(Exception e) { /* ignore */ }
System.out.println("Elapsed Time: " + (System.currentTimeMillis() - startTime));


트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://entireboy.egloos.com/tb/4196384 [도움말]

덧글

덧글 입력 영역