UDP 통신은 편지나 소포를 생각하면 된다.

즉 TCP통신처럼 연결이 통신이 끝날때까지 계속 되있지 않고 데이터를 보낸다음 연결을 끊는다.

이러한 방법은 부하를 줄이는 효과가 있다.

하지만 이러한 방법은 TCP 통신처럼 즉각적인 응답이 불가능하다. 그리고 상대편이 내가 보낸 데이터를 정상적으로 받았는지 받지 못했는지에 대한 체크를 할 수 없다.  그리고 보낸 데이터에 대한 소실 확률이 있다.

패킷 : 네트워크상에 묶어서 전송하는 것을 패킷이라고 함.

 

*UDP를 위한 자바 클래스

-DatagramPacket 클래스 (소포와 같은 클래스)

-DatagramSocket클래스(우편함과 같은 클래스)

 

-클라이언트

import java.io.*;
import java.net.*;
import java.util.*;
public class Exam_01 {
 public static void main(String[] ar) throws IOException {
  Scanner sc = new Scanner(System.in);
  System.out.print("전송할 데이터 = ");
  String data = sc.next();  //데이터의 입력을 받음.
  
  InetAddress ia = InetAddress.getByName("192.168.0.59");   //주소에 대한 객체를 만듬.
  DatagramPacket dp = new DatagramPacket(data.getBytes(), data.getBytes().length, 
    ia, 7777);    //소포에 데이터, 크기, 주소, 우편함 번호)
  DatagramSocket soc = new DatagramSocket();  //어디서 보냈는지는 중요하지 않음.
  soc.send(dp);  //소켓에 만든 데이터를 보냄.
  soc.close();  //연결을 끓음.
  System.out.println("전송끝...");
 }
}

-서버

import java.io.*;
import java.net.*;
public class Exam_02 {
 public static void main(String[] ar) throws IOException {
  byte[] by = new byte[65508];   //소포를 받을 빈공간을 만듬.
  DatagramPacket dp = new DatagramPacket(by, by.length);   //빈공간을 만듬.
  DatagramSocket soc = new DatagramSocket(7777);   //받을 우편함을 설정
  System.out.println("Server Ready...");
  soc.receive(dp);   //빈소포에 낸 내용을 받음.
  soc.close();  //연결을 끊음.
  
  System.out.println("보낸이 = " + dp.getAddress().getHostAddress());
  System.out.println("내용물 = " + new String(dp.getData()).trim());
 }
}


출처 -  http://blog.naver.com/ahrdnjsdls?Redirect=Log&logNo=150098062187 


Posted by linuxism
,