Class/socket class2014. 8. 14. 12:13
Server side
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class VarTest104 {
       public static void main(String[] args) throws IOException {
      
            ServerSocket serversocket = new ServerSocket(9999); 
//서버 소켓을 생성한다 .포트는 (9999)
            System. out .println("서버준비 완료!" );
            Socket socket = serversocket.accept(); 
// 소켓을  생성하는데 리스닝 상태로 만듬//신호를 받으면 socket에 담음
            System. out .println("클라이언트 연결 완료!" );
            InputStream in = socket.getInputStream(); 
//socket메소드중 Stream을 만드는 객채발동 서 in에 담음
            DataInputStream dis = new DataInputStream(in); //input
            OutputStream out= socket.getOutputStream(); //socket에서OutputStream
            DataOutputStream dos = new   DataOutputStream(out);//output
            
             while (true ){
                        String usrMsg = dis.readUTF();
                        System. out .println("사용자 메세지 : " +usrMsg);
                         if (usrMsg.equals("EXIT" )){
                               break ;
                        }
                        dos.writeUTF(usrMsg);
                        dos.flush(); //찌꺼기 털어주기.
            }
            dos.close();
            out.close();
            dis.close();
            in.close();
            socket.close();
            serversocket.close();
      }

}

 

Client side


 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class DataInputTest {
       public static void main(String[] args) throws IOException{
            Socket socket = new   Socket("localhost" ,9999); //클라이언트 입장입니다.
            System. out .println("서버 연결 완료!" );
            OutputStream out = socket.getOutputStream(); //socket에 기능중 Stream을 불러와 out에 담는다.
            DataOutputStream dos = new DataOutputStream(out);
            InputStream in = socket.getInputStream();
            DataInputStream dis = new DataInputStream(in);
            Scanner s = new Scanner(System. in );
            
             while (true ){
                  System. out .println("서버로 전송할 메세지를 입력해주세요.");
                  String msg =s.nextLine(); //메세지 입력
                  dos.writeUTF(msg); //OutputStream이용해서 쓴가
                  dos.flush(); // 버퍼의 내용을 전부 밀어 넣는다.
                  
                  String readMsg = dis.readUTF(); //내가 보낸 메시지 출력
                  System. out .println("받은메세지=" +readMsg);
                  
                   if (msg.equals("EXIT" )){
                         break ;
                  } //if 문
            } //while문
            dis.close();
            in.close();
            dos.close();
            out.close();
            socket.close();
      }
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class DataInputTest {
       public static void main(String[] args) throws IOException{
            Socket socket = new   Socket("localhost" ,9999); //클라이언트 입장입니다.
            System. out .println("서버 연결 완료!" );
            OutputStream out = socket.getOutputStream(); //socket에 기능중 Stream을 불러와 out에 담는다.
            DataOutputStream dos = new DataOutputStream(out);
            InputStream in = socket.getInputStream();
            DataInputStream dis = new DataInputStream(in);
            Scanner s = new Scanner(System. in );
            
             while (true ){
                  System. out .println("서버로 전송할 메세지를 입력해주세요.");
                  String msg =s.nextLine(); //메세지 입력
                  dos.writeUTF(msg); //OutputStream이용해서 쓴가
                  dos.flush(); // 버퍼의 내용을 전부 밀어 넣는다.
                  
                  String readMsg = dis.readUTF(); //내가 보낸 메시지 출력
                  System. out .println("받은메세지=" +readMsg);
                  
                   if (msg.equals("EXIT" )){
                         break ;
                  } //if 문
            } //while문
            dis.close();
            in.close();
            dos.close();
            out.close();
            socket.close();
      }
}

'Class > socket class' 카테고리의 다른 글

ServerSocket Class(java)  (0) 2014.08.14
Java-TCP(Server,Client) 프로그램 작성  (0) 2014.08.12
자바를 이용한 TCP소켓프로그래밍..  (0) 2014.03.23
Posted by wrnly
Class/socket class2014. 8. 14. 11:42
 
서버 구현의 기본은 특정한 로컬 포트에 대해 ServerSocket 객체를 열고 클라이언트가 연결해 오기를 기다리는 것이다.
클라이언트가 연결해 올때마다 ServerSocket은 각각의 클라이언트 연결에 대해 Socket 객체를 생성한다.  
ServerSocket은 대개 InputStream이나 OutputStream을 통해 클라이언트와 데이터를 주고 받는다.
Port번호는 1~65535까지 사용 가능하며 이중 1~1023 까지는 시스템 서비스 용으로 예약 되어있다.



소켓 생성시 포트 번호를 0으로 주는 것은 시스템에서 알아서 포트를 할당 하라는 의미이다.
ServerSocket 객체가 생성되자 마자 운영체제가 클라이언트로 부터 연결을 받을 준비를 한다. 클라이언트가 시도한 연결은 Queue에 들어가며 서버가 accept 메소드를 호출하면 하나씩 큐에서 빠져 나온다.
ServerSocket 생성시 몇 개의 연결을 Queue에 넣을 것인지 지정 할 수 있다.




Constructor
ServerSocket(int port)  
Creates a server socket on a specified port.  
The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.  




Constructor
ServerSocket(int port, int backlog)  
Creates a server socket and binds it to the specified local port number, with the specified backlog.  
The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused


서버 소켓 생성시 인자없는 생성자는 BIND 되지 않은 서버소켓을 만들며 인자로 포트번호를 준 경우에는 그 포트번호를 이용해 BIND된 서버 소켓을 만든다.(포트번호는 1에서 65535까지이며 0인 경우는 아무숫자나 활당하라는 의미이다.)
backlog라는 인자를 지정하지 않으면 default로 50이 지정되며 지정된 수를 넘어서면 접속을 거부 당한다.
서버소켓을 생성시 InetAddress형을 주는 경우는 서버에 Network Card가 여러 개 있는 경우이다.




서버소켓(ServerSocket)의  accept()메소드는 BIND된 서버 소켓에게 접속을 기다리도록 지시한다. 그래서 접속을 해오는 소켓이 있을때 까지 이 메소드는 blocking되기 때문에 접속이 있을때까지 마냥 기다리게 된다. 속
서버소켓(ServerSocket)에서 가장 중요한 메소드는 accept() 메소드이며 보통 네크웍 프로그래밍을 할때 accept() 메소드를 이용하여 많은 접속을 받아 들이므로 이런 코드는 Thread의 run() 메소드안에 있는 경우가 대부분 이다.




------------ Server Process Model

1) ServerSocket을 생성 - ServerSocket(포트번호, 큐의 크기)
서버 소켓은 클라이언트의 접속을 받는 부분
포트번호는 서버 프로세스가 갖는 구별 번호. 시스템에서는 216개를 정의하여 사용. 0~1024:슈퍼유저용, 1024~4000:예약, 4000~65535:사용 권고
FTP:21, telnet:23, E-mail:25, HTTP:80
큐의 크기는 서버에 한 번에 접속이 가능한 클라이언트의 수를 결정
2) 클라이언트의 접속을 받아 들임 ? Socket=ServerSocket.accept()
클라이언트로부터 들어오는 신호가 있는 지를 감시(listen)하여 클라이언트와의 접속을 개시. 접속이 완료된 시점에서 소켓이 만들어 짐



3) 클라이언트와 자료를 전송하고 수신함
생성된 소켓에서 출력 스트림(자료 전송용)과 입력 스트림(자료 수신용)을 받아서 사용.
4) 연결을 종료함
전송과 수신이 완료되면 클라이언트와의 연결을 끊게 되고 다른 클라이언트에게 서비스를 함.



------------------------ Client Process Model

1) Socket을 생성  
Socket(호스트 이름, 포트번호)
호스트 이름 : 서버 프로세스가 설치되어  
있는 시스템의 이름. 자신의 시스템인 경우  
“localhost”를 이용
2) 서버와 자료를 전송하고 수신
생성된 소켓에서 출력 스트림(자료 전송용)과 입력 스트림(자료 수신용)을 받아서 사용.
3) 연결을 종료
전송과 수신이 완료되었으면 서버와의 연결을 끊게됨




------------------------------- LocalPortScanner.java

import java.net.*;  
import java.io.*;  
public class LocalPortScanner {  
public static void main(String[] args) {  
  for (int port = 1; port <= 65535; port++) {  
try {  
ServerSocket server = new ServerSocket(port);  
}  
  catch (IOException e)  {  
    System.out.println("There is a server on port " + port + ".");  
}    
  }  
    }  
}  
Posted by wrnly
Class/socket class2014. 8. 12. 17:04

복사 http://blog.naver.com/ksh81850/220006254007


● TCP 프로그램

- TCP 프로그램은 신뢰성(데이터 100%전송)이 보장.
- UDP방식(신뢰성 전무,오직 전송)보다 많이 사용

- ServerSocket 클래스와 Socket 클래스로 구성

 

● TCP 소켓의 처리 방식

- 아래 그림과 같다.

1. 클라이언트가 클라이언트의 Socket을 생성한다

2. ServerSocket의 Accept() 메서드가 클라이언트의 접속 요청을 확인한다

3. 서버가 서버의 Socket이 하나 생성시킨다.

4. 새로 생성된 서버 Socket은 클라이언트의 Socket과 연결된다.

 

● ServerSocket 클래스의 구성

- 생성자

ServerSocket(int port)

- 클라이언트의 요청을 받아들일 포트(Port)번호를 가지고 ServerSocket 객체 생성

- 메서드

Socket accept()

- 클라이언트 요청을 받아들인 다음 Socket 객체 생성 후 return

void close()

- Server Socket을 닫는다

● ServerSocket 클래스의 특징

- port 번호를 가지고 데몬(무한 루프를 수행. 클라이언트의 요청을 기다린다) 실행

- accept() 메서드는 클라이언트가 접속 요청시, 클라이언트와 연결된 Socket 생성

 

● Socket 클래스의 구성

- 실질적 데이터 교환은 Socket 클래스 이용

- 생성자

Socket(String host, int port)

Socket(InetAddress addr, int port)

- host : 접속할 서버의 IP 주소

- port : 접속할 포트 번호

- addr : 접속할 서버의 InetAddress 객체

- 메서드

InputStream getInputStream()

- 현 소켓과 관련된 InputStream 객체 return

- 현 접속 컴퓨터의 데이터를 수신할수 있도록 한다 

OutputStream getOutputStream()

- 현 소켓과 관련된 OutputStream 객체 return

- 현 접속 컴퓨터에 데이터를 송신할수 있도록 한다 

void close()

- 현 소켓 닫는다

InetAddress getInetAddress()

- 현 소켓 연결된 원격 컴퓨터의 InetAddress 객체 return

InetAddress getLocalAddress()

- 현 소켓 연결된 지역 컴퓨터의 InetAddress 객체 return

int getPort()

- 현 소켓 연결된 컴퓨터의 포트 번호 return

int getLocalPort()

- 현 소켓 연결된 지역 컴퓨터의 포트번호 return

 

● TCP 프로그램 작성 과정

- 아래 그림과 같다.

- 서버는 ServerSocket클래스의 Accept 메서드가 클라이언트의 Socket 접속을 기다린다

- 클라이언트는 서버 접속위해 Socket() 생성

- Accept() 메서드는 Socket을 생성해 I/O 스트림을 생성(입출력을 위해)

- 서버측 Socket의 Read는 클라이언트측 Socket의 Write 메서드를 통해 데이터를 수신

- 서버측 Socket의 Write는 클라이언트측 Socket의 Read 메서드를 통해 데이터를 전송 

 

● Server와 Client를 만드는 예제 1.

- 시간 전송하는 ServerClient 제작

※ xp는 시간 자동 설정 기능 제공. 네트워크 내 서버와 클라이언트 사이 현 시스템 시간 동기화 가능(그렇지만 필자는 windows 7이므로 7기준으로 제작)

- Server

public static void main(String[] args) throws Exception {
        int port = 1218;
        ServerSocket server_socket = new ServerSocket(port);
        while(true){

            System.out.println("서버 시작");

            Socket client = server_socket.accept();
            OutputStream os = client.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);       
            oos.writeObject(new Date());
            oos.flush();
            oos.close();
            client.close();
        }
    }?

- ServerSocket(int port) 을 바탕으로 ServerSocket을 생성

- ObjectOutputStream 클래스를 이용해 객체를 직렬화 시킨다(예제 결과 후 설명)

- Date 클래스 생성자를 이용 현 서버 시간을 Date 객체 형태로 클라이언트에 전송

- flush 를 통해 강제로 데이터를 클라이언트에 전송. flush 하지않을경우, 버퍼 내용이 차야지만 자동으로 데이터를 전송처리하므로, 정확히 발송 시점을 알수 없으므로, 강제적으로 전송하는편이 좋다.

- 결과화면

- 클라이언트가 접속하지 않을경우, 서버시작 한번만 나오지만 클라이언트가 한번 접속한 후, 접속을 끊었으므로 서버는 데몬상태이므로 2번 출력되었다.

- 클라이언트가 다시 접속할때까지 accept() 메서드에서 대기중이다. 

-Client

?public static void main(String[] args) throws Exception {
        String server_ip;
        Date date = null;
        int port=1218;
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("서버 시간 받아오기 ");
        System.out.print("타임 서버 아이피 입력 : ");
        server_ip = read.readLine();
        Socket client = new Socket(server_ip,port);
        InputStream is = client.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        date = (Date)ois.readObject();
        System.out.println("현 시간 : "+date);
        ois.close();
        client.close();
    }

- Socket(InetAddress addr, int port) 생성자를 통해 클라이언트의 Socket을 생성한다. Port번호ip주소가 틀릴경우 예외 발생하므로 throws Exception을 통해 예외처리를 해주었다

- 서버의 데이터를 받기위해 getInputStream 메서드를 이용해 객체 생성.

- 서버에서 ObjectOutputStream을 통해 객체 직렬화를 한 상태이므로 ObjectInputStream을 통해 객체 역직렬화를 한다.

- Object형태의 데이터를 받음으로, 기존의 형태캐스트(형변환)해주어야 한다.

- 결과 화면

 

● ObjectOutputStream / ObjectInputStream

- 객체 직렬화

- 메모리에 있는 객체를 보조기억장치에 저장할수 있도록 바이트 형태로 전환
- 즉, 객체(메모리에 있는)다른곳(보조기억장치) 전송을 위해 스트림 이용하여 바이트 데이터로 변환

- 직렬화 하는 이유

- 객체가 생성되어 적재되는 메모리는 순간적이기 때문에 영구적으로 보관하기 위해 직렬화 사용

- ObjectOutputStream

- 객체를 파일에 기록 가능한 클래스

- 객체의 데이터를 직렬화 시켜주는 메서드

- Serializable 인터페이스로 구현 안되있다면 NotSerializableException 예외 발생

- 보통 직렬화 데이터 저장 파일 확장자는 'ser'로 저장

- ObjectInputStream

- 직렬화 된 객체를 읽어오는 클래스

- 객체의 데이터 복원시켜주는 메서드로 역 직렬화 시켜주는 메서드

- Serializable 인터페이스

- 모든 멤버변수가 직렬화의 대상이 된다.

- 객체 스트림을 통해 직렬화시, 멤버변수가 직렬화

- 멤버변수 중 직렬화의 대상에서 제외시키려면 transient 키워드 사용 




Posted by wrnly
Class/url class2014. 8. 12. 16:59

복사 http://blog.naver.com/ksh81850/220004196289


● URL(Uniform Resource Locator)

- URL은 도메인 네임을 사용해 컴퓨터에 있는 문서로 접근할때 사용하는 것

- 도메인 네임이란 인터넷을 쉽게 사용할수 있도록 IP번호에 이름 부여한 것.

- 인터넷에 있는 정보의 위치를 표기하기 위한 표준적 방법

 

● URL의 사용 형식

- URL의 형식에는 프로토콜, 인터넷 주소, 포트 번호, 파일 경로 등이 사용된다. 

- 프로토콜://인터넷 주소[:포트번호][/디렉토리 이름[/파일 이름]]

 

● URL의 기본 특징

- 프로토콜과 인터넷 주소는 대.소문자 구별하지 않는다

- 디렉토리 이름과 파일 이름은 대.소문자 구별한다

- URL 사용 형식에서 대괄호([]) 부분은 생략 가능

- 포트번호 생략시(Well-known port) 번호 사용

- 파일 경로 생략시 기본 파일인 index.html 파일 요청

 

● URL의 사용 예시

- 웹

프로토콜 : http

기본 포트번호 : 80

http://www.naver.com

- Telnet 

프로토콜 : telnet

기본 포트번호 : 23

telnet://chollian.net

- FTP

프로토콜 : ftp

기본 포트번호 : 21

ftp://ftp.netscape.com

- Gopher

프로토콜 : gopher

기본 포트번호 : 70

gopher://gopher.kornet.net

 

● URL 클래스

- Java내 URL 처리하고 싶을때 URL 클래스를 사용한다.

 

● URL 클래스의 생성자의 구성

- URL(String protocol, String host, int port, String file)

- URL(String protocol, String host, String file) 

- URL(String urlString)

▶ protocol : 프로토콜(ex: http://)

▶ host : 컴퓨터 이름(ex: www.naver.com) 

▶ port : 포트 번호(ex: 80) 

▶ file : URL에 존재하는 파일 이름

▶ urlString ; 모든 요소를 모팜한 문자열

 

● URL 클래스의 메서드의 구성

- String getFile()

- URL 파일 이름 return

- String getHost()

- URL 호스트 이름 return

- String getPort()

- URL 포트 이름 return

- String getProtocol()

- URL 프로토콜 이름 return

- String toExternalForm()

- 전체 URL 문자열 return

- URLConnection openConnection()

- URL 연결 후, URLConnection 객체 return

- InputStream openStream()

- URL 정보 읽기 위한 InputStream 객체 return 

  URL에 자세한 정보는 URLConnection 클래스 사용하면 된다.

- 사용시, URL 지정된 페이지의 내용을 자신의 컴퓨터에 저장 가능.


● URLConnection클래스의 메서드의 구성

- int getContentLength()

- 문서 길이 return

- String getContentType()

- 문서 타입 return

- long getDate()

- 문서 생성일 return

- long getExpiration()

- 문서 제거일 return

- long getLastModified()

- 문서 마지막 수정 날짜 return

- InputStream getInputStream()

- 문서 읽기 위한 InputStream 객체 return

 

● URL 클래스의 메서드를 통한 간단한 예제 1.

- URL 정보 분석하는 예제

import java.io.*;
import java.net.*; 

public static void main(String[] args) throws Exception{
        String url_str = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("URL page 입력 >> ");
        url_str = br.readLine().trim();
        System.out.println(url_str);
        URL url = new URL(url_str);
        System.out.println("프로토콜 : "+url.getProtocol());
        System.out.println("포트번호 : "+url.getPort());
        System.out.println("호스트      : "+url.getHost());
        System.out.println("URL 내용 : "+url.getContent());
        System.out.println("파일경로 : "+url.getFile());
        System.out.println("URL 전체 : "+url.toExternalForm());
}

- 사용자로부터 URL 정보를 입력받는다.(문자열의 좌우 여백 공간 제거(trim으로 인해)

- ex)   String temp = "       trim   ";

String temp_trim = temp.trim();

name_trim의 저장된 내용은 "trim" 이 저장된다

- URL(String urlString) 생성자를 이용하여 URL 객체를 생성한다.

- 결과화면

 

 

● URLConnection 클래스의 메서드를 통한 간단한 예제 1.

- 웹 사이트 문서를 컴퓨터로 가지고오는(문서 정보 출력) 예제

public static void main(String[] args) throws Exception {
        String url_string = null;
        int size = 0;
        int ch;
        URL url = null;

        URLConnection url_read=null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input the Web site : ");
        url_string = reader.readLine().trim();
        url = new URL(url_string);
        url_read = url.openConnection();
        size = url_read.getContentLength();
        System.out.println("문서 타입 : "+url_read.getContentType());
        System.out.println("수정 일자 : "+url_read.getLastModified());
        System.out.println("문서 크기 : "+size+"byte");
        if(size > 0){
            InputStream is = url_read.getInputStream();
            while((ch=is.read())!=-1){
                System.out.print((char)ch+" ");
            }
            is.close();
        }
    }

- reader.readLine().trim()은 해당 입력 문자열의 좌우 공백을 없애주고 나머지를 반환한다는 뜻이다.

- 간단한 예제를 보자

String url_string = null;
   
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input char : ");
        url_string = reader.readLine().trim();
        System.out.println(url_string);

- 결과화면

- 입력은 문자열 맨앞 맨뒤 공백이 존재. 출력은 공백 제거

- getContentLength()는 URLConnection 메서드로서, 전체크기 return

- Byte 단위

- InputStream is = url_read.getInputStream() 는 is 객체를 url_read의 메서드를 통해 지정하여 url_read의 데이터값을 읽어오는 역할을 한다.

- url = new URL(url_string)는  URL(String urlString)의 생성자를 바탕으로 url_string이 올바르지 않다면 에러가 발생한다. 그로인해 예외처리를 해줘야 하는데 throws Exception 통해 예외처리를 한다는 것을 알수 있다.

- 결과화면


 

● URLConnection 클래스의 메서드를 통한 간단한 예제 2.

- 위의 예제 속도를 개선 하는 예제

- 위의 예제는 속도가 느릴수 밖에 없다. 이유는 InputStream의 read() 메서드를 통해 한글자씩 읽어와 출력하기때문이다. 개선해보자.


InputStream is = url_read.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(is);

String temp = null;

while((temp=br.readLine())!=null){
                System.out.print(temp+" ");
}
br.close()?;


- 위의 동일한 코드에서 해당하는 부분만 일부 수정한 부분이다.

- BufferedReader를 통해 한글자씩 읽고 출력하는 것이 아닌 한 라인을 읽고 출력하는 것으로 바꾼것을 알수 있다.

- br.close() -> InputStream 을 닫아주는 것이 아닌 BufferedReader를 닫아줌으로써 둘다 닫는 역할을 한다.

- 결과 화면은 위와 동일하다.



'Class > url class' 카테고리의 다른 글

Java-Network에 관한-InetAddress클래스  (0) 2014.08.12
Posted by wrnly
Class/url class2014. 8. 12. 16:54

복사 http://blog.naver.com/ksh81850/220003557425


● InetAddress 클래스

- IP 주소 처리할때 사용하는 클래스.

- 자신의 IP 주소 확인하기 위해서는 시작 -> 실행 -> cmd -> ipconfig -all 을 통해 확인 가능.

 

● InetAddress 클래스 메서드의 구성

- Boolean equals(InetAddress other)

- other 객체와 같은 주소를 갖으면 true, 그렇지 않으면 false

- byte[] getAddress()

- 주소를 갖고 있는 4개 요소의 바이트 배열 return

- String getHostAddress()

- 주소 정보를 나타내는 문자열 return

- String getHostName()

- 자신의 컴퓨터 이름 return

- InetAddress getLocalHost()

- 자신의 컴퓨터 InetAddress 객체 return

- InetAddress getByName(String host)

- host로 지정된 컴퓨터를 나타내는 InetAddress 객체 return

- InetAddress[] getAllByName(String host)

- host로 지정된 모든 컴퓨터 InetAddress 객체로 반환(하나 도메인으로 여러 컴퓨터 작동시)

 

● InetAddress 클래스 특징

- 생성자를 이용한 객체 생성 불가(일반적인 방법으로)

- 생성위해 get메서드를 통해 도메인네임과 ip주소를 이용하여 생성해야 한다.

ex)

InetAddress inet = InetAddress.getByName("?Naver.com");

InetAddress inet = InetAddress.getByName("?125.209.222.141");?

// 해당 IP주소는 Naver.com입니다.?

- 동일한 정보를 입력해야 한다.?

?

● InetAddress 클래스의 메서드를 통한 간단한 예제 1.

- 특정 도메인 네임과 IP 주소 정보를 출력하는 예제?

import java.net.*;?

?public static void main(String[] args) throws UnknownHostException{
      InetAddress fir_add1 = InetAddress.getByName("naver.com");
      InetAddress sec_add2 = InetAddress.getByName("125.209.222.141");
      InetAddress my_add = InetAddress.getLocalHost();
  
      System.out.println("first_address = "+fir_add1.getHostAddress());
      System.out.println("second_address = "+sec_add2.getHostName());
      System.out.println("my_address = "+my_add.getHostAddress());
      System.out.println("my_name = "+my_add.getHostName());
 }

- 네트워크에 관련된 것을 접근하기 위해선 java.net.* 반드시 import 해야 한다.

- ?throws UnknownHostException 을 해주는 이유는 InetAddress 클래스의 객체 생성시 잘못된 도메인 네임과 IP주소를 사용할 경우 UnknownHostException 에러 발생하기 때문에 throws를 통해 예외처리를 시킨 것이다.

- "도메인 네임"을 입력하여 객체 생성시킬수 있다.

- "IP 주소"를 입력하여 객체 생성 시킬수 있다.?

?- 객체 생성 된 것의 IP주소를 출력

- 해당 결과

 

● InetAddress 클래스의 메서드를 통한 간단한 예제 2.

- 웹 사이트 도메인 네임 입력(사용자)하여 해당 IP 주소 출력하는 예제?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;?

public static void main(String[] args) throws Exception{
      String url = null;
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Input the Web site : ");
      url = reader.readLine();
      InetAddress web_addr = InetAddress.getByName(url);
      System.out.println(url+"_ip_address = "+web_addr.getHostAddress());
 }?

- ?throws UnknownHostException 을 할 경우는 InetAddress 클래스의 객체 생성시 잘못된 도메인 네임과 IP주소를 사용할 경우의 UnknownHostException 에러 발생은 예외처리가 정상적으로 되지만, readLine에 해당하는 예외처리가 불가능 하므로 둘다 예외처리 가능한 Exception으로 한 것이다.?

?- 객체 생성 된 것의 IP주소를 출력

- 결과 화면

 

● InetAddress 클래스의 메서드를 통한 간단한 예제 3.

?- 하나의 도메인 이름으로 설정된 모든 컴퓨터의 IP 주소 확인하는 예제

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;?

?public static void main(String[] args) throws Exception {
      String url = null;
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Input the Web site : ");
      url = reader.readLine();
      InetAddress [] web_addr = InetAddress.getAllByName(url);
      System.out.println(url+" : "+web_addr.length + "개의 IP 주소가 존재");
      for(int i=0;i<web_addr.length;i++){
            System.out.println((i+1)+"번 ip주소 : "+web_addr[i].getHostAddress());
      }
 }

?- ?throws UnknownHostException 을 할 경우는 InetAddress 클래스의 객체 생성시 잘못된 도메인 네임과 IP주소를 사용할 경우의 UnknownHostException 에러 발생은 예외처리가 정상적으로 되지만, readLine에 해당하는 예외처리가 불가능 하므로둘다 예외처리 가능한 Exception으로 한 것이다.?

?- 여러개의 이름을 저장하기 위해 배열로 선언했고, AllByName을 이용했다.

- 배열의 개수를 확인

?- 해당 배열 객체 생성 된 것의 IP주소를 출력?

?- 결과 화면

?



'Class > url class' 카테고리의 다른 글

Java-Network에 관한-URL클래스  (0) 2014.08.12
Posted by wrnly
Class/socket class2014. 3. 23. 21:20

TCPClient.java ====================


import java.io.*;
import java.net.*;
class TCPClient {
public static void main (String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = 
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence=inFromServer.readLine();

System.out.println("Length of the srting : "+ modifiedSentence.length());
System.out.println("FROM SERVER : " + modifiedSentence);

clientSocket.close();
}
}



TCPServer.java ===========================================================




import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String reversedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);
while(true){
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
char[] array = clientSentence.toCharArray();
int len = array.length;

char[] tosend = new char[len];
for(int i = 0; i < len; i ++)
tosend[i] = array[len - i];

reversedSentence = new String(tosend);
outToClient.writeBytes(reversedSentence + '\n');
}
}
}

Posted by wrnly