What are some best practices for handling UDP socket connections in PHP to avoid "connection refused" errors?

When working with UDP socket connections in PHP, it is important to handle potential "connection refused" errors by properly checking for errors and implementing error handling mechanisms. One way to avoid these errors is to ensure that the socket connection is properly established before attempting to send or receive data. Additionally, implementing retry mechanisms or using non-blocking sockets can help mitigate connection issues.

<?php
$server = 'udp://127.0.0.1';
$port = 1234;

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($socket === false) {
    die("Error creating socket: " . socket_strerror(socket_last_error()));
}

if (!socket_connect($socket, $server, $port)) {
    die("Error connecting to server: " . socket_strerror(socket_last_error()));
}

// Send data
$message = "Hello, UDP server!";
socket_sendto($socket, $message, strlen($message), 0, $server, $port);

// Receive data
socket_recvfrom($socket, $data, 1024, 0, $from, $port);
echo "Received response from $from: $data\n";

socket_close($socket);
?>