#JAVA SERVER #JAVA CLIENT

#MULTICAST #UNICAST #BROADCAST

#TCP/IP #SOCKET #SERVERSOCKET

 

* 설명 :

( ex. N - 큰 의미, n - 좁은 의미)

1. 브로드캐스트란?(1:N 통신)

   - 데이터를 여러 방향으로 동시에 전송하여 동일 IP그룹에 있는 컴퓨터라면 데이터를 수신할 수 있는 방식이다.

 

2. 멀티캐스트란?(1:n통신)

- 다중의 수신 대상자들에게 보내는 방식이다.

 

3. 유니캐스트란?(1:1 통신)

- 특정한 대상 수신자에게만 보내는 방식이다.

 

 

#1. 클라이언트 단

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;

public class Ex01MulticastClient {

 public static void main(String[] args) {
  
  DatagramPacket packet = null;
  MulticastSocket socket = null;
  
  try {
   socket = new MulticastSocket(9006);
   System.out.println("클라이언트 생성.");
   
   // 그룹에 조인(라우터가 보냄)
   InetAddress address = InetAddress.getByName("224.128.1.5"); // 멀티 캐스트를 위한 아이피 설정
   socket.joinGroup(address);
   
   byte[] buf = new byte[512];
   
   packet = new DatagramPacket(buf, buf.length);
   
   while (true) {
    // 패킷 수신
    socket.receive(packet);

    String msg = new String(packet.getData(), 0, packet.getLength());
    System.out.println("수신 > " + msg);
   }
   
  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


 

#2. 서버 단

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Ex01MulticastServer {

 public static void main(String[] args) {
  
  DatagramPacket packet = null;
  MulticastSocket socket = null;
  
  try {
   socket = new MulticastSocket();
   System.out.println("서버 생성 성공.");
   
   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   
   // IPv4 아래의 내용은 이전의 포스팅을 통해 설명 해두었음.
   // A Class : 0000 (0000) => 0.0.0.0 ~ 127.255.255.255
   // B Class : 1000 (0000) => 128.0.0.0 ~ 191.255.255.255
   // C Class : 1100 (0000) => 192.0.0.0 ~ 223.255.255.255
   // D Class : 1110 (0000) => 224.0.0.0 ~ 239.255.255.255
   // E Class : 1111 (0000) => 240.0.0.0 ~ 255.255.255.255
   InetAddress address = InetAddress.getByName("224.128.1.5"); // 멀티캐스트 방식으로 서버 주소를 설정함.

   
   while(true) {
    System.out.print("입력 : ");
    String msg = reader.readLine();
    
    if(msg==null) {
     break;
    }
    
    packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, address, 9006);
    
    socket.send(packet);
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

+ Recent posts