목차 소켓이란 무엇인가 Socket클래스의 생성자 소켓에 관한 정보 알아내기 소켓 닫기 소켓 옵션 설정하기 소켓 예외

Slides:



Advertisements
Similar presentations
All Rights Reserved, Copyright© UBIVELOX co.,Ltd LG U+ 과금 API 소개 Version1.0 Authorubivelox Date21-Feb
Advertisements

Python Essential 세미나 1 Socket Programming 발표자 : 임민상 ( 화 )
제 4 장 인터넷 창병모 네트워크 구성 2 LAN(Local Area Network) LAN  근거리 통신망으로 집, 사무실, 학교 등의 건물과 같이  가까운 지역을 한데 묶는 컴퓨터 네트워크 이더넷 (Ethernet)  제록스 PARC.
Python Socket/HTTP overmania. 목표  소켓을 이용하여 기본적인 서버 - 클라이언트 모델을 구현할 수 있다.  간단한 웹서버를 소켓을 이용하여 작성할 수 있다.
Computer Network Lab 다중전송 소켓 컴퓨터 네트워크 실험실 이 희 규, 조 한 진.
키보드 보안 순천향대학교 정보보호학과 임강빈 교수.
Chap15 네트워킹 Section 1 : 네트워킹의 개요와 java.net 패키지 Section 2 : 인터넷 주소와 URL
어서와 Java는 처음이지! 제3장선택과 반복.
11장. 프로토콜 핸들러 AI &HC I LAB 김 성 현.
28강 JAVA 입출력(I/O) 알아보기 - 입출력(I/O) 이란? - JAVA 입출력 API(Input~, Output~)
Java Socket 통신 이개혁 정대준.
네트워크 프로그래밍 Youngnam Kim.
Domain Name System.
컴퓨터 응용 및 실습 Part1. OOP&Java Programming data type Review
TCP/IP 네트워크 제 26 장 Telnet과 Rlogin 정보통신연구실.
3 장 인터넷 서비스.
Understanding of Socket and File I/O
Chapter 7 Networking.
8장. 네트워크 프로그래밍 /*컴퓨터 네트워크 프로그래밍 -김화종 저- 참조 */
제14장 원격 메소드 호출 김 기 환. 조 명 휘.
22 장 프로세스간 전달 : UDP와 TCP 22.1 프로세스간 전달 22.2 사용자 데이터그램 프로토콜
자바 서버 API와 서블릿 데이타베이스 실험실 이찬섭, 박용문.
Chapter 11 – 예외 처리 Outline 11.1 설계 쟁점 11.2 Pl/I의 예외 처리 11.3 Ada의 예외 처리
Chap11 네트워킹 11.1 네트워킹의 개요와 java.net 패키지 11.2 인터넷 주소와 URL 11.3 TCP 소켓
Web Servers (IIS & Apache)
제 4장 주소변환 프로토콜 (ARP : Address Resolution Protocol)
제 18 장 TCP/IP 연결 확립과 종료 정보통신연구실.
8장 자바 입출력.
Network Lab. Seoung Hyeon, Lee
호스트이름과 네트워크이름 찾기 (Hostname and Network Name Lookups)
6장 비연결형 지향 프로토콜 Database Lab 강 우 석.
제 30 장 다른 TCP/IP 응용.
JAVA 프로그래밍 12장 네트워킹(Networking).
10장 SafeTalk 시스템 소프트웨어 연구실 성순화 이재일
Chapter 07 소스코드의 취약점 분석.
자바 5.0 프로그래밍.
Choi Seong Yun 네트워크 프로그래밍 Choi Seong Yun
Using Standard I/O on Sockets
명품 JAVA Programming 제 16 장 네트워크.
명품 Java Programming.
Processing resulting output
Embeded 기초 다지기 2015년 10월 26일 intern Sally
10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성
5. 네트워킹 사용자 표시 : users/ rusers/who/w users 지역 호스트 상에 있는 사용자의 간단한 목록 표시
제 14 장 도메인 네임 시스템 정보통신연구실.
Department of Computer Engineering
제 21 장 TCP 타임아웃과 재전송.
Chapter 8 연결형 프로토콜 서버 발표자 : SE Lab 황 성 하
Department of Computer Engineering
중간 결과 보고 ( Server & Client )
제 21 장 TCP 타임아웃과 재전송 정보통신연구실.
제9장 네트워킹 숙명여대 창병모 2011 가을.
주소록 프로그램.
Network Programming(1)
자바 5.0 프로그래밍.
8장 서버 소켓 프로그래밍 언어 실험실 석사 3학기 김성중.
15장 네트워킹 15.1 네트워킹의 개요와 java.net 패키지 15.2 인터넷 주소와 URL 15.3 TCP 소켓
제 2장 어휘구조와 자료형 토 큰 리 터 럴 주 석 자 료 형 배 열 형.
제8장 네트워킹 숙명여대 창병모
Transmission Control Protocol (TCP)
User Datagram Protocol (UDP)
컴퓨터공학실습(I) 3주 인공지능연구실.
자바 5.0 프로그래밍.
Operating System Multiple Access Chatting Program using Multithread
Java 3장. 자바의 기본 구조 I : 변수, 자료형, 연산자 public class SumTest {
시스템 인터페이스 Lab3 Unix 사용법 실습.
Internet 인공지능연구실
제2부 3장 인터넷 인터넷 ( a global network of networks )
Department of Computer Engineering
임베디드 프로그래밍 Lecture #
Presentation transcript:

발표자 : 김진광, 정창모 PL Lab, Simul Lab 7장 클라이언트 소켓 발표자 : 김진광, 정창모 PL Lab, Simul Lab

목차 소켓이란 무엇인가 Socket클래스의 생성자 소켓에 관한 정보 알아내기 소켓 닫기 소켓 옵션 설정하기 소켓 예외 유용한 프로그램들 PL Lab

소켓이란 무엇인가 인터넷상의 데이터들은 데이터그램이라 불리는 한정된 크기의 패킷형태로 존재 데이타그램은 헤더와 페이로드(payload)로 구성 헤더 : 목적지 주소와 포트번호, 출발지 주소와 포트번호 및 기타정보 포함 페이로드 : 실제 데이터 포함 문제점 실제 데이터 전송시 데이터그램의 크기가 한정되어 있기 때문에 이보다 큰 데이터들은 여러 패킷으로 나누어져서 전송 따라서 패킷중 일부가 소멸, 데이터 손상시의 재전송, 순서재조정 필요 데이터를 전송하는 과정 : 데이터를 여러 개의 패킷으로 나눔, 헤더를 붙임, 도착한 패킷의 헤더를 구문분석, 도착한 패킷과 도착하지 못한 패킷을 조사 이를 처리하는 프로그램이 복잡해짐 PL Lab

소켓이란 무엇인가(계속) 해결책 소켓 : 네트워크 작업을 바이트 단위로 읽고 쓸 수 있는 스트림처럼 처리 데이터를 전송하는 과정을 소켓이 처리해준다. 소켓은 유닉스의 주요 개념에 대한 확장 모든 I/O는 사용자가 키보드를 사용하건, 그래픽 디스플레이를 하건 실제 파일을 처리하건 네트워크작업을 하건간에 파일의 I/O와 유사해야 한다. 버클리 유닉스의 발명품 추상화 프로그래머는 네트워크의 낮은 수준에 일어나는 매체타입, 패킷크기, 패킷의 재전송, 네트워크 주소등을 몰라도 된다. 버클리 유닉스의 초기 버전 뿐만아니라, 그 이후 무수한 변종들이 사용되어짐. 윈도우, 매킨토시, 자바등에 이용됨 PL Lab

소켓이란 무엇인가(계속) 소켓의 기본적인 작업 원격 기계에 접속 (데이터를 보내고 받을 준비를 한다.) 데이터를 보낸다. 데이터를 받는다. 연결을 끊는다. 포트에 바인드 한다. 들어오는 데이터에 귀를 기울인다. (listen) 바인드 된 포트를 통해 들어오는 원격 기계의 접속 요청을 받는다. 자바의 Socket클래스는 클라이언트와 서버 프로그램에 함께 사용되며 클라이언트 프로그램에서 상위 4개의 일을 담당한다. 소켓의 사용 방식 Socket() 생성자를 이용하여 새로운 소켓이 만들어진다. 소켓은 원격 호스트에 접속을 시도한다. 연결이 이루어지면, 원격 호스트와 로컬 호스트는 소켓으로부터 각각 입력 및 출력 스트림을 얻어서 이것을 서로 데이터를 주고 받는데 사용한다. 전송되는 데이터를 프로토콜에 따라 다름(http서버와 ftp서버) 전송이 끝나면, 어느 한쪽에서 또는 양쪽에서 연결을 끊는다. PL Lab

소켓이란 무엇인가(계속) 텔넷으로 프로토콜 탐색하기 프로토콜이 어떻게 작동하는지 알기 위해, 텔넷을 사용하여 서버에 접속한 후, 서버가 이해하는 명령어를 입력하여 그 응답을 확인 텔넷은 기본적으로 포트번호 23번을 사용 SMTP는 전자 메일을 전송하기 위한 프로토콜 예 : telnet localhost 25 로컬기계의 포트번호 25인 SMTP 포트에 접속 PL Lab

소켓이란 무엇인가(계속) 텔넷으로 프로토콜의 탐색 예 [cse:/lab/kimjk] telnet localhost 25 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 220 cse.hannam.ac.kr ESMTP Sendmail 8.9.3/8.9.3; Thu, 11 May 2000 11:57:44 +0900 (KST) helo ce.hannam.ac.kr 250 cse.hannam.ac.kr Hello localhost [127.0.0.1], pleased to meet you mail from : mdlee@ce.hannam.ac.kr 250 mdlee@ce.hannam.ac.kr... Sender ok rcpt to : kimjk@cse.hannam.ac.kr 250 kimjk@cse.hannam.ac.kr... Recipient ok data 354 Enter mail, end with "." on a line by itself 안녕하십니까.. 이 메일은 테스트용입니다. 안녕 . 250 LAA14645 Message accepted for delivery quit 221 cse.hannam.ac.kr closing connection Connection closed by foreign host. PL Lab

소켓이란 무엇인가(계속) 텔넷으로 프로토콜의 탐색 결과 [cse:/lab/kimjk] mailx mailx version 5.0 Tue Jul 15 21:29:48 PDT 1997 도움말 필요시 ? 입력. "/var/mail/kimjk": 1개 메시지 1개 신규 >N 1 mdlee@ce.hannam.ac Thu May 11 11:59 14/443 ? 1 Message 1: From mdlee@ce.hannam.ac.kr Thu May 11 11:59 KST 2000 Date: Thu, 11 May 2000 11:58:09 +0900 (KST) From: mdlee@ce.hannam.ac.kr 안녕하십니까.. 이 메일은 테스트용입니다. 안녕 ? quit /lab/kimjk/mbox에 1개 메시지가 보관됨 [cse:/lab/kimjk] PL Lab

Socket클래스의 생성자 public Socket(String host, int port) throws UnknownHostException, IOException public Socket(InetAddress host, int port) throws IOException public Socket(String host, int port, InetAddress interface, int localPort) throws IOException public Socket(InetAddress host, int port, InetAddress interface, int localPort) throws IOException protected Socket() protected Socket(SocketImpl) PL Lab

Socket클래스의 생성자(계속) pubic 생성자 protected 생성자 호스트는 InetAddress나 String형태로 지정 포트 번호는 0과 65535 사이의 값중에서 int 형태로 지정 로컬 호스트와 로컬 포트 번호를 지정해 주어야 함, 이들은 데이터의 출발지에 대한 정보를 제공함 여러 개의 IP주소를 갖고 있는 경우, 특정한 네트워크 인터페이스를 선택하고자 할 때에는 로컬 호스트를 지정해 주어야함 protected 생성자 네트워크 클라이언트와 서버는 이 생성자를 사용할 필요가 없다. 암호화, 인증, 데이터 압축등의 기능을 구현하기 위해 Socket클래스의 서브 클래스를 만드는 경우는, 이 생성자를 사용 PL Lab

Socket클래스의 생성자(계속) public Socket(String host, int port) throws UnknownHostException, IOException 지정된 호스트의 지정된 포트에 대해 소켓을 생성하여 원격 호스트에 접속을 시도 try { Socket toOra = new Socket(“www.ora.com”, 80); } catch(UnknownHostException e) { System.err.println(e); catch(IOException e) { 호스트 이름이 알려져 있지 않거나, 서버가 작동하고 있지 않을경우 소켓이 열리지 않을경우. 서버가 접속을 거부 로컬호스트의 인터넷연결문제 라우팅에 문제로 인한 패킷의 전달 불가 PL Lab

Socket클래스의 생성자(계속) 예제 7-2 : 0부터 1024번의 포트 중에서 TCP 서버로서 사용중인 것을 알아내기 for (int i=0; i<1024;i++) { try { theSocket = new Socket(host, i); System.out.println("There is a server on port" + i + "of" + host); } catch (UnknownHostException e) { System.err.println(e); break; catch (IOException e) { PL Lab

Socket클래스의 생성자(계속) 예제 7-2 의 결과 [cse:/lab/kimjk/java] java lookForPorts There is a server on port7 of localhost There is a server on port9 of localhost There is a server on port13 of localhost There is a server on port19 of localhost There is a server on port21 of localhost There is a server on port23 of localhost There is a server on port25 of localhost There is a server on port37 of localhost There is a server on port79 of localhost There is a server on port80 of localhost There is a server on port110 of localhost There is a server on port111 of localhost There is a server on port512 of localhost There is a server on port513 of localhost There is a server on port514 of localhost There is a server on port515 of localhost There is a server on port540 of localhost [cse:/lab/kimjk/java] 위의 포트들에서 무슨 서버가 실행되고 있는지 알려면 텔넷을 실행하라. 유닉스 시스템의 경우 이 정보를 /etc/services 파일에서 찾을수 있다. PL Lab

Socket클래스의 생성자(계속) 예제 7-2 의 결과(계속) [cse:/lab/kimjk/java] java lookForPorts ce.hannam.ac.kr There is a server on port7ofce.hannam.ac.kr There is a server on port9ofce.hannam.ac.kr There is a server on port13ofce.hannam.ac.kr There is a server on port19ofce.hannam.ac.kr There is a server on port21ofce.hannam.ac.kr There is a server on port23ofce.hannam.ac.kr There is a server on port25ofce.hannam.ac.kr There is a server on port37ofce.hannam.ac.kr There is a server on port80ofce.hannam.ac.kr There is a server on port110ofce.hannam.ac.kr There is a server on port111ofce.hannam.ac.kr There is a server on port139ofce.hannam.ac.kr There is a server on port513ofce.hannam.ac.kr There is a server on port514ofce.hannam.ac.kr There is a server on port901ofce.hannam.ac.kr PL Lab

Socket클래스의 생성자(계속) public Socket(InetAddress host, int port) throws IOException 앞의 생성자와 다른점은 인자로 InetAddress 객체 (4장 참고)를 쓴다는 점이다. 하나의 호스트에 대하여 여러개의 소켓을 생성하여 연결 할 경우 효율적 InetAddress ORA=null; Socket ORASocket; try { ORA = new InetAddress(“www.ora.com”) } catch (UnknownHostException e) { System.err.println(e); ORASocket = new Socket(ORA,80); catch(IOException e) { PL Lab

Socket클래스의 생성자(계속) 예제 7-3 : 포트번호 1024이상에대해서 TCP서버가 실행중인 것을 찾아내기 try { InetAddress theAddress = InetAddress.getByName(host); for (int i=1024; i < 65536; i++) { theSocket = new Socket(theAddress, i); System.out.println("There is a server on port" + i + " of " + host); } catch (IOException e) { catch (UnknownHostException e) { System.err.println(e); PL Lab

Socket클래스의 생성자(계속) 예제 7-3 결과 [cse:/lab/kimjk/java] java lookForPorts2 There is a server on port1103 of localhost There is a server on port1726 of localhost There is a server on port4045 of localhost There is a server on port6000 of localhost There is a server on port6112 of localhost There is a server on port7100 of localhost There is a server on port32771 of localhost There is a server on port32772 of localhost There is a server on port32773 of localhost There is a server on port32774 of localhost There is a server on port32775 of localhost There is a server on port32776 of localhost There is a server on port32778 of localhost There is a server on port32779 of localhost There is a server on port32780 of localhost There is a server on port33128 of localhost [cse:/lab/kimjk/java] PL Lab

Socket클래스의 생성자(계속) 예제 7-3 결과(계속) [cse:/lab/kimjk/java] java lookForPorts2 ce.hannam.ac.kr There is a server on port1726 of ce.hannam.ac.kr There is a server on port2049 of ce.hannam.ac.kr There is a server on port3306 of ce.hannam.ac.kr There is a server on port3751 of ce.hannam.ac.kr There is a server on port3752 of ce.hannam.ac.kr There is a server on port3753 of ce.hannam.ac.kr There is a server on port4045 of ce.hannam.ac.kr There is a server on port6000 of ce.hannam.ac.kr There is a server on port6112 of ce.hannam.ac.kr There is a server on port7100 of ce.hannam.ac.kr There is a server on port8080 of ce.hannam.ac.kr There is a server on port22370 of ce.hannam.ac.kr There is a server on port32771 of ce.hannam.ac.kr There is a server on port32772 of ce.hannam.ac.kr There is a server on port32773 of ce.hannam.ac.kr There is a server on port32774 of ce.hannam.ac.kr There is a server on port32776 of ce.hannam.ac.kr There is a server on port32779 of ce.hannam.ac.kr There is a server on port32780 of ce.hannam.ac.kr There is a server on port32781 of ce.hannam.ac.kr There is a server on port32782 of ce.hannam.ac.kr There is a server on port32784 of ce.hannam.ac.kr There is a server on port56238 of ce.hannam.ac.kr [cse:/lab/kimjk/java] PL Lab

Socket클래스의 생성자(계속) public Socket(String host, int port, InetAddress interface, int localPort) throws IOException public Socket(InetAddress host, int port, InetAddress interface, 지정된 호스트의 지정된 포트에 대해 TCP 소켓을 생성하여 원격 호스트에 접속을 시도함 앞의 두 인자가 가리키는 호스트와 포트번호에 접속 뒤의 두 인자가 가리키는 네트워크 인터페이스와 로컬 포트로부터 접속 마지막 인자인 localPort에 0의 값이 넘겨지면 1024와 65,535사이에서 사용 가능한 포트 번호를 무작위로 추출하여 사용 이를 익명 포트(anonymous port)라 한다. 예) calzone.oit.edu에 서 프로그램 실행시, 네트워크 인터페이스가 2개가 있다. 하나는 100메가 비트의 FDDI(sunsite.unc.edu)인터페이스이고, 다른 하나는 초당 10메가 비트의 이더넷 인터페이스이다. 이때 전자를 사용한 경우는 다음과 같다. PL Lab

Socket클래스의 생성자(계속) InetAddress sunsite; Socket ORASocket; try { } sunsite = new InetAddress(“Sunsite.unc.edu”); } catch (UnknownHostException e) { System.err.println(e); ORASocket = new Socket(“www.ora.com ”, 80, sunsite,0); catch (IOException e) { PL Lab

소켓에 관한 정보 알아내기 소켓은 SocketImpl이라는 단 하나의 필드를 갖고 있다. 아래와 같은 메소드를 사용하여 이 필드에 접근한다. public InetAddress getInetAddress() public int getPort() public int getLocalPort() public InetAddress getLocalAddress() public InputStream getInputStream() throws IOException public OutputStream getOutputStream() throws IOException PL Lab

소켓에 관한 정보 알아내기(계속) 예제 7-4 : 소켓의 정보를 알아내기 try { Socket theSocket = new Socket(args[i], 80); System.out.println( "Conneted to " + theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress()); } catch (UnknownHostException e) { System.err.println("I can't find" + args[i]); } catch (SocketException e) { System.err.println("Could not connect o " + args[i]); } catch (IOException e) { System.err.println(e); } PL Lab

소켓에 관한 정보 알아내기(계속) 예제 7-4 결과 D:\java\7장>java getSocketInfo cse.hannam.ac.kr Conneted to cse.hannam.ac.kr/203.247.40.31 on port 80 from port 1242 of COOLNOTE /203.247.40.172 D:\java\7장> [cse:/lab/kimjk/java] java getSocketInfo ce.hannam.ac.kr Conneted to ce.hannam.ac.kr/203.247.36.37 on port 80 from port 40976 of cse.hann am.ac.kr/203.247.40.31 [cse:/lab/kimjk/java] java getSocketInfo cse.hannam.ac.kr Conneted to cse.hannam.ac.kr/203.247.40.31 on port 80 from port 40977 of cse.han nam.ac.kr/203.247.40.31 PL Lab

소켓에 관한 정보 알아내기(계속) public InputStream getInputStream() throws IOException 소켓으로부터 프로그램으로 들어오는 원시 데이터를 ImputStream형태로 반환한다. 대개의 경우, ImputStream은 좀더 많은 기능을 제공하는 DataInputStream으로 연결이 된다 실제 테스트를 위해 RFC867에서 규정된 “day/time” 프로토콜을 사용해 보자 day/time 서버는 13번 포트로 소켓을 연다. 이 프로토콜 테스트를 위한 텔넷의 사용 [cse:/lab/kimjk] telnet localhost 13 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Thu May 11 13:35:06 2000 Connection closed by foreign host. [cse:/lab/kimjk] PL Lab

소켓에 관한 정보 알아내기(계속) 예제7-5 : daytime 프로토콜 클라이언트 try { theSocket = new Socket(hostname, 13); theTimeStream = new DataInputStream(theSocket.getInputStream()); String theTime = theTimeStream.readLine(); System.out.println( "It is " + theTime + " at " + hostname); } 결과 [cse:/lab/kimjk/java] java daytimeClient It is Thu May 11 14:04:44 2000 a tlocalhost [cse:/lab/kimjk/java] java daytimeClient ce.hannam.ac.kr It is Thu May 11 14:05:05 2000 at ce.hannam.ac.kr [cse:/lab/kimjk/java] PL Lab

소켓에 관한 정보 알아내기(계속) public OutputStream getOutputStream() throws IOException 애플리케이션에서 소켓의 다른 끝점으로 데이터를 보내기 위해 사용되는 원시 OutputStream을 반환한다. 이것은 사용되기 전에, 보다 많은 기능을 제공하는 DataOutputStream과 같은 스트림 클래스에 연결된다. 실제 테스트를 위해 RFC862에서 규정된 echo 프로토콜을 사용해 보자 echo 서버는 7번 포트로 소켓을 연다. 이 프로토콜 테스트를 위한 텔넷의 사용 [cse:/lab/kimjk] telnet localhost 7 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. This is a test ^] telnet> close Connection closed. [cse:/lab/kimjk] PL Lab

소켓에 관한 정보 알아내기(계속) 예제 7-6 : echo 클라이언트 echo 프로토콜을 구현하기 위해 getOUtputSteam()과 getInputStream()을 사용 사용자가 마침표를 입력하면 프로그램 종료 try { theSocket = new Socket(hostname, 7); theInputStream = new DataInputStream(theSocket.getInputStream()); theOutputStream = new PrintStream(theSocket.getOutputStream()); userInput = new DataInputStream(System.in); while (true) { theLine = userInput.readLine(); if (theLine.equals(".")) break; theOutputStream.println(theLine); System.out.println(theInputStream.readLine()); } } PL Lab

소켓에 관한 정보 알아내기(계속) 예제 7-6 결과 [cse:/lab/kimjk/java] java echoClient This is a test This is a kim's test . [cse:/lab/kimjk/java] [cse:/lab/kimjk/java] java echoClient ce.hannam.ac.kr This is a test2 This is a anotertest PL Lab

소켓에 관한 정보 알아내기(계속) 객체 메쏘드 public String toString() Socket 클래스는 java.lang.Object 클래스에서 받은 메소드 중 toString()만을 치환(override)한다. toString은 다음과 같은 문자열을 반환한다. Socket [addr=www.ora.com/198.112.208.11, port=80, localport=50055] PL Lab

소켓 닫기 public Synchronize void close() throws IOException 지금까지는 소켓이 자동적으로 닫힌다고 가정해 왔다. 소켓은 스스로 제거하지는 않고 프로그램이 종료하거나 프로그램의 쓰레기 수거(garbage collection)가 시작되면 소켓이 닫힌다. 소켓을 시스템에서 닫아주기를 바라는 것은 바람직하지 못하다. 특히 프로그램이 얼마나 오랫동안 실행될지 알 수 없는 경우에는 더더욱 그러하다. try { Socket theSocket = new Socket(“www.ora.com” ,13); theSocket.close(); } catch(UnknownHostException e) { System.err.println(e); catch(IOException e) { PL Lab

소켓 옵션 설정하기 소켓에는 아래와 같은 5가지의 옵션이 있다. TCP_NODELAY SO_BINDADDR IP_MULTICATS_IF SO_TIMEOUT SO_LINGER public void getTcpNoDelay(boolean on) throws SocketException public boolean getTcpNoDelay() throws SocketException true 로 설정해 두면 가능한 빠르게 패킷들을 전송 서버로 데이터를 전송하기 전에, 서버로부터 응답패킷이 올때까지 기다림, TCP_NODELAY를 true로 셋팅해 놓으면 위의 버퍼링 기능을 중단시키고 false로 하면 버퍼링기능을 실행시킨다. 예 : if (is.getTcpNoDelay()) s.setTcpNoDelay(ture) PL Lab

소켓 옵션 설정하기 (계속) SO_LINGER public void setSoLinger(boolean on, int seconds) throws SocketException public boolean getSoLInger() throws SocketException 소켓이 닫혔을 때 아직 보내지지 않고 대기하고 있는 패킷이 있다면 이를 어떻게 처리할 것인가를 결정 기본적으로 close() 메쏘드는 소켓이 닫히자마자 남아있는 패킷을 모두 버린다 SO_LINGER를 ture로 만들면 지정된 시간동안 기다리게 되며 대기 시간을 –1로 만들면 남아있는 모든 패킷을 전송할 때까지 기다리게 된다. 예 : 4분의 대기시간을 설정 if(s.getSoLinger()!=-1) s.setSoLinger(true, 240); PL Lab

소켓 옵션 설정하기 (계속) SO_TIMEOUT public synchronized void setSoTimeout(int ms) throws SocketException public synchronized int getSoTimeout() throws SocketException 소켓으로부터 들어오는 데이터를 읽기 위해 read()메쏘드를 호출한 경우, 이 메소드는 들어오고 있는 모든 데이터를 읽을 때까지 block된다. SO_TIMEOUT을 설정해 두면 일정시간까지 기다리고 그 시간이 지나면 InterruptedException이 발생한다. 프로그래머는 이 예외 상항에 대비해야 한다. 초과 시간은 밀리초(milli seconds)단위이며 0으로 설정할 경우 무한시간을 의미한다. 예 : 초과 시간을 3분으로 설정하는 경우 if (s.getSoTimeout() == ) s.setSoLinger (180000); PL Lab

소켓 예외 자바 1.0에서 소켓 메쏘드가 실패하면 java.io.IOException의 서브 클래스인 SocketException이 발생한다. 예외 상황에 대한 더 정확한 정보를 제공하는 SocketException의 서브클래스가 3개가 있다. BindException : 이미 사용중이거나 사용이 허락되지 않는 로컬 포드에서 Socket 또는 ServerSocket객체를 생성하려고 할때 발생 ConnectException : 호스트가 바쁘거나, 요청된 포트에서 서비스가 제공되지 않기 때문에 연결 요청을 거부할 때 발생 NoRouteToHostException : 연결이 시간 초과 되었음을 가리킨다. PL Lab

유용한 프로그램들 Finger 소켓을 이용한 응용 프로그램인 클라이언트 어플리케이션 이 프로토콜 테스트를 위한 텔넷의 사용 한줄로 된 질의를 보내면 서버는 그에 대해 응답을 하고, 연결을 끊는다. 전송되는 모든 데이터는 ISO-LAtin-1텍스트이고 한쌍의 복귀 개형(carriage return)/줄바꿈(line feed)(\r\n)으로 끝나야 한다. PL Lab

유용한 프로그램들(계속) finger 프로토콜 테스트 [ce:/user/msphd/kimjk]# telnet localhost 79 Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused [ce:/user/msphd/kimjk]# telnet cse.hannam.ac.kr 79 Trying 203.247.40.31... Connected to cse.hannam.ac.kr. Escape character is '^]'. Login Name TTY Idle When Where kimjk Kim Jin Kwang pts/4 3 Fri 16:16 203.247.40.172 btpark ??? dtremote 1:01 Fri 15:26 pc166:0 Connection closed by foreign host. [ce:/user/msphd/kimjk]# enter PL Lab

유용한 프로그램들(계속) 예제 7-8 : 자바의 명령어 방식 finger 클라이언트 try { theSocket = new Socket(hostname, port, true); ps = new PrintStream(theSocket.getOutputStream()); for (int i=1; i<args.length; i++) ps.print(args[i]+ " "); ps.print("\r\n"); theFingerStream = new DataInputStream(theSocket.getInputStream()); String s; while ((s=theFingerStream.readLine()) != null) { System.out.println(s); } catch (IOException e) { System.err.println(e); PL Lab

유용한 프로그램들(계속) 예제 7-8 결과 D:\java\7장>java finger cse.hannam.ac.kr kimjk Login Name TTY Idle When Where kimjk Kim Jin Kwang pts/4 9 Fri 16:16 203.247.40.172 D:\java\7장>java finger cse.hannam.ac.kr D:\java\7장>java finger cse.hannam.ac.kr btpark btpark ??? dtremotepc1 <May 5 15:26> pc166:0 D:\java\7장> PL Lab

유용한 프로그램들(계속) Whois 간단한 디렉토리 서비스 프로토콜로 RFC954에 규정되어있음 인터넷 호스트와 도메인을 책임지고 있는 관리자를 추적하기위해 설계 whois 클라이언트는 중앙 서버들 중에 한 곳에 접속하여 개인 또는 개인들에 대한 디렉토리 정보를 요청한다. 중앙 집중식으로 운영 whois 프로토콜 테스트 : 교제 216페이지 참조 [cse:/lab/kimjk/java] telnet whois.internic.net 43 Trying 198.41.0.6... Connected to rs.internic.net. Escape character is '^]'. Harold Whois Server Version 1.1 ... HAROLD.FRUGAL.COM HAROLD.ORG HAROLD.NET HAROLD.COM .... Connection closed by foreign host. [cse:/lab/kimjk/java] PL Lab

유용한 프로그램들(계속) 예제 7-11 : 명령어 방식의 whois 클라이언트 try { theSocket = new Socket(hostname, port, true); ps = new PrintStream(theSocket.getOutputStream()); for (int i=0; i<args.length;i++) ps.print(args[i] + " "); ps.print("\r\n"); theWhoisStream = new DataInputStream(theSocket.getInputStream()); String s; while ((s = theWhoisStream.readLine())!=null) { System.out.println(s); } catch (IOException e) { System.err.println(e); PL Lab

유용한 프로그램들(계속) who예제 7-11 결과 D:\java\7장>java whois ora.com Whois Server Version 1.1 Domain names in the .com, .net, and .org domains can now be registered with many different competing registrars. Go to http://www.internic.net for detailed information. Domain Name: ORA.COM Registrar: NETWORK SOLUTIONS, INC. Whois Server: whois.networksolutions.com Referral URL: www.networksolutions.com Name Server: AUTH03.NS.UU.NET Name Server: NS.OREILLY.COM Updated Date: 27-oct-1999 >>> Last update of whois database: Sat, 6 May 00 03:59:17 EDT <<< The Registry database contains ONLY .COM, .NET, .ORG, .EDU domains and Registrars. PL Lab

유용한 프로그램들(계속) 표 7-1 : whois 접두어들 도메인 레코드만 찾아라 게이트웨이 레코드만 찾아라 그룹 레코드만 찾아라 호스트 레코드만 찾아라 네트워크 레코드만 찾아라 조직 레코드만 찾아라 개인 레코드만 찾아라 익명 시스템 번호 레코드만 찾아라 핸들 값과 일치하는 레코드만 찾아라 전자 메일 주소와 일치하는 레코드만 찾아라 이름과 일치하는 레코드만 찾아라 그룹레코드만 찾아서 그 그룹안에 속해있는 개일들을 보여달라 각각의 검색결과에 대해 상세한 정보를 보여달라 주어진 문자열로 시작하는 레코드만 찾아라 검색결과가 단 한건만 있더라도 요약된 내용을 보여달라 지정된 호스트와 지정된 네트워크상의 호스트들을 사용자에게 보여달라 Domain Gateway Group Host Network Organization PERSONAL ASN Handle 또는 ! Mailbox 또는 @ Name 또는 : Expand 또는 ‘*’ Full 또는 = Partial 또는 suffix Summary 또는 $ SUBdisplay 또는 % 의미 접두어 PL Lab

유용한 프로그램들(계속) 예제 7-12 : whois 클라이언트의 그래픽 버전 결과 PL Lab