【问题标题】:How can I create a simple UDP client-server-communication in Java?如何在 Java 中创建简单的 UDP 客户端-服务器通信?
【发布时间】:2014-04-16 11:59:51
【问题描述】:

在哪里可以找到有关 Java 中 UDP 的详细信息以及如何建立基本的 UDP 通信?

【问题讨论】:

    标签: java networking udp client-server


    【解决方案1】:

    This page 提供有关如何创建 UPD 服务器和客户端的详细信息。

    本质上,您可以像这样创建一个服务器

    // Setup the socket
    DatagramSocket socket = new DatagramSocket(12345);
    
    // Receive a packet
    byte[] buffer = new byte[512];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    socket.receive(packet);
    
    // Do something with the data in the buffer
    // and if necessary receive more packets
    
    // Close the socket
    socket.close();
    

    客户端端,您可以像这样发送一个数据包:

    // Create a socket
    DatagramSocket socket = new DatagramSocket();
    
    // Create a buffer and fill it with your data
    byte[] buffer = new byte[512];
    ...
    
    // Send the packet
    InetAddress address = InetAddress.getByName("127.0.0.1");
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 12345);
    socket.send(packet);
    
    // Close the socket
    socket.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多