Working with DatagramSocket in Java for UDP communication requires attention to best practices to ensure reliability and efficiency. Here are some best practices to follow:
Here’s a simple example of a UDP client and server using DatagramSocket:
// UDP Server
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
// UDP Client
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, UDP Server!";
byte[] sendData = message.getBytes();
InetAddress serverAddress = InetAddress.getByName("localhost");
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9876);
socket.send(sendPacket);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
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?