Search code examples
pythonphpsocketsservicepython-asyncio

PHP socket_recv return not human readable response


i have a service in python and another application on web server.

I send socket and agent get it process it and return response to web server.

But result can not readable.

agent picture

see, i send data human readable.

web server picture

and result on web server.

    public static function request($command, $json_decode = true)
    {
        if (!globals('agent-durum')) return false;
        $end_line_msg = '«--the-end-line--»';
        try {
            if (gettype($command) == 'array') $command = json_encode($command, JSON_UNESCAPED_UNICODE);

            // $command .= $end_line_msg;

            $socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            @socket_connect($socket, self::$settings['ip'], self::$settings['port']);
            @socket_write($socket, $command, strlen($command));

            $max_len = 65495;
            $total_response = '';
            while ($bytes = @socket_recv($socket, $response, $max_len, 0x20)) {
                $total_response .= str_replace($end_line_msg, '', $response);
                if ($max_len > $bytes || strstr($response, $end_line_msg)) break;
            }

            var_dump($total_response);

            if ($total_response == '-not-support-') abort(500, 'Agent bu isteği desteklemiyor.');
            if ($total_response == '') abort(500, self::errmsg());

            try {
                if ($json_decode) return json_decode($total_response, true);
            } catch (\Throwable $_err) {
            }

            return $total_response;
        } catch (\Throwable $err) {
            Cache::remove('agent-check-cache');
            return false;
        }
    }
 def data_received(self, data):
        message = data.decode()
        log('Data received: {!r}'.format(message))

        result = self.type_parse(json.loads(message))

        send = f'{result}{end_line}'
        log('Data sending.')
        self.transport.write(send.encode())
        if len(result) < 12000:
            log(f'Data is sent: {result}')
        else:
            log(f'Data is sent. (data is big)')

        log('Close the client socket')
        self.transport.close()

agent return data and i need same "sent" and "see's data."


Solution

  • I found the problem:

    i revise that:

    while ($bytes = @socket_recv($socket, $response, $max_len, 0x20)) {
        $total_response .= str_replace($end_line_msg, '', $response);
        if ($max_len > $bytes || strstr($response, $end_line_msg)) break;
    }
    

    to this:

    while (true) {
        $response = socket_read($socket, $max_len);
        $total_response .= str_replace($end_line_msg, '', $response);
        if (strstr($response, $end_line_msg)) break;
    }
    

    and this work for me.