What are the best practices for ensuring compatibility and proper data handling between PHP and C# in socket communication?

When working with socket communication between PHP and C#, it is important to ensure compatibility and proper data handling by using a standardized data format such as JSON. This allows for easy serialization and deserialization of data between the two languages. Additionally, both PHP and C# should use the same encoding and decoding methods to prevent any data corruption during transmission.

// PHP code snippet for sending data to a C# socket server using JSON format
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$json_data = json_encode($data);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '127.0.0.1', 8888);
socket_write($socket, $json_data, strlen($json_data));
socket_close($socket);