DatagramSocket in Java is a class that enables communication using the User Datagram Protocol (UDP). It allows for the sending and receiving of packets, or datagrams, over a network without establishing a connection. This method of communication is typically used in scenarios where speed is more critical than reliability, such as video streaming or online gaming.
DatagramSockets operate by providing a simple interface to send and receive packets, making it an essential tool for network programming in Java. Each datagram sent contains its own destination address and port number, allowing for direct communication with other services.
Below is a simple example of using a DatagramSocket to send and receive messages:
// Sender
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSender {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, World!";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876);
socket.send(packet);
socket.close();
}
}
// Receiver
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceiver {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String receivedMessage = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + receivedMessage);
socket.close();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?