如何根据传入的UDP数据包大小动态分配缓冲区大小?

时间:2019-02-12 18:54:16

标签: java udp

这是我第一次进行UDP通信,我不知道我的知识是否不足或者我要参考的文档没有足够的信息。

我有一个客户端服务器应用程序。服务器应该发送警报消息,客户端应该建立连接,只要该应用程序处于活动状态,它就会处于活动状态,接收通知并提取实际消息(显示给用户)。我能够发送邮件并由我的客户接收。

我有一个问题:

  1. 我将2K分配给接收者的缓冲区(byte[] buf = new byte[2048];)。在大多数情况下,可能就足够了。但是,如果后端发送的字符超过2048个,我该怎么办? Doc说长度是动态的,因此我没有上限。

我的客户代码:

public class UDPClient {
    private DatagramSocket udpSocket;
    private InetAddress serverAddress;
    private int port;
    private Scanner scanner;

    private UDPClient(String destinationAddr, int port) throws IOException {
        this.serverAddress = InetAddress.getByName(destinationAddr);
        this.port = port;
        udpSocket = new DatagramSocket(this.port);
        scanner = new Scanner(System.in);
    }

    public static void main(String[] args) throws IOException {
        UDPClient sender = new UDPClient("192.168.1.102", 8888);
        print("-- Running UDP Client at " + InetAddress.getLocalHost() + " --");
        sender.listen();
    }

    private void listen() throws IOException {
        String msg;

        String in = scanner.nextLine();
        DatagramPacket p = new DatagramPacket(in.getBytes(), in.getBytes().length, serverAddress, port);
        this.udpSocket.send(p);

        while (true) {
            byte[] buf = new byte[2048];
            DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddress, port);

            // blocks until a packet is received
            udpSocket.receive(packet);
            msg = new String(packet.getData()).trim();

            print("Message from " + packet.getAddress().getHostAddress() + ": " + msg);
            parseNotification(msg);
        }
    }

    private static void print(String message) {
        System.out.println(message);
    }

    private void parseNotification(String notification) {
        byte[] actual = notification.getBytes();
        print("Actual length: " + actual.length);

        byte[] response = UDPResponse.hexStringToByteArray(notification);
        Message message = getMessageFromEASNotification(response);
        print("Final message in json:");
        print(message.toString());
    }
}

0 个答案:

没有答案