2021-08-11

This commit is contained in:
2021-08-11 22:04:37 +09:00
parent 36c5ddbe9e
commit 95b002cada

View File

@@ -11,24 +11,48 @@ import lombok.extern.slf4j.Slf4j;
import java.io.IOException; import java.io.IOException;
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.MulticastSocket; import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
@Slf4j @Slf4j
public class MulticastUdpClientSample { public class MulticastUdpClientSample {
public static void main(String... args) throws IOException { public static void main(String... args) throws IOException {
new Thread() {
@Override
public void run() {
try {
client("ONE");
} catch (IOException e) {
log.error("Oops", e);
}
}
}.start();
new Thread() {
@Override
public void run() {
try {
client("TWO");
} catch (IOException e) {
log.error("Oops", e);
}
}
}.start();
}
public static void client(String name) throws IOException {
MulticastSocket socket = new MulticastSocket(18888); MulticastSocket socket = new MulticastSocket(18888);
InetAddress group = InetAddress.getByName("224.0.0.1"); InetAddress group = InetAddress.getByName("224.0.0.1");
socket.joinGroup(group); socket.joinGroup(group);
// 수신 for (int i = 0; i < 10; i++) {
byte[] buf = new byte[256]; // 수신
DatagramPacket packet = new DatagramPacket(buf, buf.length); byte[] buf = new byte[256];
socket.receive(packet); DatagramPacket packet = new DatagramPacket(buf, buf.length);
String received = new String(packet.getData(), 0, packet.getLength()); socket.receive(packet);
log.info("Rx: {}", received); String received = new String(packet.getData(), 0, packet.getLength());
log.info("{} Rx: {}", name, received);
}
socket.leaveGroup(group); socket.leaveGroup(group);
socket.close(); socket.close();