UDP Channel

UDP๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„  DatagramChannel ์„ ์ด์šฉํ•ด ์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

DatagramChannel datagramChannel = DatagramChannel.open(StandardProtocolFamily.INET);

How do send?

์ฑ„๋„์„ ์—ฐ๋’ค, send()๋ฅผ ์ด์šฉํ•˜์—ฌ buffer๋ฅผ ์ „์†กํ•  ์ˆ˜ ์žˆ๋‹ค.

public class Main {
    public static void main(String[] args) throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open(StandardProtocolFamily.INET);

        System.out.println("Server started");

        ByteBuffer buffer = Charset.defaultCharset().encode("Hello Junny");
        datagramChannel.send(buffer, new InetSocketAddress("localhost", 7788));
        System.out.println("Send to server ");

        System.out.println("Close to server");
        datagramChannel.close();
    }
}

How to receive?

์ฑ„๋„์„ ์—ฐ๋’ค, bind() ๋กœ ์ฑ„๋„์˜ ํฌํŠธ๋ฅผ ์ง€์ •ํ•ด์ค๋‹ˆ๋‹ค.

receive๋Š” Blocking์ด๋ฏ€๋กœ ์‘๋‹ต์ด ์˜ฌ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฝ๋‹ˆ๋‹ค.

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        DatagramChannel datagramChannel = DatagramChannel.open(StandardProtocolFamily.INET);

        datagramChannel.bind(new InetSocketAddress(7788));

        new Thread(() -> {
            System.out.println("Start Server");

            System.out.println("Waiting Client");
            while (true) {
                try {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(10000);
                    SocketAddress receive = datagramChannel.receive(byteBuffer);
                    System.out.println("Client Message: " + UTF_8.decode(byteBuffer));
                } catch (IOException e) {
                    System.out.println("Close Server");
                    throw new RuntimeException(e);
                }
            }
        }).start();


        Thread.sleep(1000000L);
        datagramChannel.close();
    }
}

Last updated