netty(五)nio之UDP 一、UDP簡介 二、示例代碼

一、UDP簡介

UDP是User Datagram Protocol的縮寫。

即使是出現網絡擁堵的情況下,UDP也無法進行流量控制等避免網絡擁塞的行爲。此外,傳輸途中即使出現丟包,UDP也不負責重發。甚至當出現包的到達順序亂掉時也沒有糾正的功能。

由於UDP面向無連接,它可以隨時發送數據。再加上UDP本身的處理既簡單又高效,因此經常用於以下幾個方面:

1)包總量較少的通信(DNS、SNMP等)
2)視頻、音頻等多媒體通信(即時通信)
3)限定於LAN等特定網絡中的應用通信

二、示例代碼

使用UDP需要注意一下兩點:
1)UDP是面向無連接的,client發送數據不會管server是否開啓,也不關注是否成功失敗。
2)server這邊的receive方法會將接收到的數據存入bytebuffer,但如果數據報文超過buffer大小,多出來的數據會被默默拋棄。

服務端代碼如下:

public class ServerTest {

    public static void main(String[] args) {
        // 開啓UDP channel
        try (DatagramChannel channel = DatagramChannel.open()) {
            // 綁定端口
            channel.socket().bind(new InetSocketAddress(9999));
            System.out.println("waiting...");
            ByteBuffer buffer = ByteBuffer.allocate(32);
            // 接收消息,並寫入buffer,此處方法阻塞
            channel.receive(buffer);
            // 切換buffer爲讀模式
            buffer.flip();
            System.out.println(print(buffer));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static String print(ByteBuffer b) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < b.limit(); i++) {
            stringBuilder.append((char) b.get(i));
        }
        return stringBuilder.toString();
    }
}

客戶端代碼:

public class ClientTest {

    public static void main(String[] args) {
        // 開啓UDP channel
        try (DatagramChannel channel = DatagramChannel.open()) {
            // 初始化buffer,內容是hello
            ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
            // 綁定服務端
            InetSocketAddress address = new InetSocketAddress("localhost", 9999);
            // 推送消息
            channel.send(buffer, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如上代碼所示,其中客戶端的recieve方法時阻塞的,直到接收到消息。

服務端結果輸出如下所示:

waiting...
hello

即使客戶端啓動時,服務端沒有啓動,客戶端也不會有任何異常。


關於UDP這裏只做簡單的介紹和使用方法,有用話,兄弟們點個贊~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章