如何在Java中创建简单的UDP客户端 - 服务器通信?

时间:2014-04-16 11:59:51

标签: java networking udp client-server

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

1 个答案:

答案 0 :(得分:5)

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();