|
//소켓통신을 이용하여 다른 호스트에 접속시 응답이 없는 경우
//Connection Timeout Exception이 발생할 때 까지 계속 기다릴 수가 //있습니다. 빠른 응답을 요구하는 시스템에서는 Exception이 발생할 때 //까지 무작정 기다릴 수 없으므로 일정시간 동안만 기다리는 경우가 //필요할 수 있습니다. 아래는 Thread를 이용하여 원하는 시간만큼 //기다리는 예제이니 참고 하세요~ import java.net.Socket; import java.io.IOException; public class SocketConnect implements Runnable { long timeout; String hostname; int port; Socket socket = null; boolean isTimeOut = false; public SocketConnect (long timeout) { this.timeout = timeout; } public Socket createSocket(String hostname, int port) { this.hostname = hostname; this.port = port; this.socket = null; Thread t = new Thread(this); t.setDaemon(true); t.start(); //Timeout까지 기다림 끝나지 않으면 중단 //Thread t가 끝날때 까지 기다림(Timeout 시간 동안) //즉 run 메소드가 수행된 후 기다리는데 정상적인 경우 주어진 3초안에 //소켓 접속이 이루어 지지만 실패하는 경우엔 socket이 null 임 try { t.join(timeout); } catch(InterruptedException ie) { t.interrupt(); } //TimeOut 기간동안 Socket 접속을 못한 경우 if (socket == null) { isTimeOut = true; throw new IOException("socket time out! "); } return socket; } public void run() { try { socket = new Socket(hostname, port); } catch(IOException ioe) { } if (isTimeOut) { try { if (socket != null) socket.close(); } catch(IOException ioe) { } socket = null; } return; } public static void main(String[] args) { try { SocketConnect s = new SocketConnect(3000); //3초 동안 기다림 s.createSocket("www.oraclejavanew.kr", 23); } catch(Exception e) { e.printStackTrace(); } } } |
2015년 10월 12일 월요일
Socket 접속시 Timeout 설정하기
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기