Where can I find details on UDP in Java and how is a basic UDP communcation established?
1 Answer
This page provides detailed information on how to create a UPD server and client.
In essence, you create a server like this:
// 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(); On the client side, you can then send a packet like this:
// 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();