What are the key differences between TCP and UDP protocols in PHP?
The key differences between TCP and UDP protocols in PHP are that TCP is connection-oriented, ensuring data delivery and ordering, while UDP is connectionless, allowing for faster transmission but with no guarantee of delivery or order. In PHP, when working with TCP, you would typically use the stream_socket_client function to establish a connection and communicate with a server. When working with UDP, you would use the socket_create and socket_sendto functions to send data to a specific destination without establishing a connection.
// TCP example
$socket = stream_socket_client('tcp://example.com:80', $errno, $errstr, 30);
fwrite($socket, 'Hello, TCP server!');
$response = fread($socket, 1024);
fclose($socket);
// UDP example
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_sendto($socket, 'Hello, UDP server!', strlen('Hello, UDP server!'), 0, 'example.com', 1234);
socket_close($socket);