Python SSL socket error: ssl.SSLWantReadError: The operation did not complete (read)

Python SSL socket error: ssl.SSLWantReadError: The operation did not complete (read)

我有一个通过自签名证书使用 SSL 的普通服务器。我正在尝试使用 Python 3.4.2 SSL 套接字库通过以下脚本创建连接和 return 数据并出现相关错误:

import socket, ssl

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

ssl_socket = ssl.wrap_socket(s, keyfile="/path/to/server.pem", certfile="/path/to/client.pem", cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1_2, ca_certs="/path/to/client.pem")

ssl_socket.connect(('hostname', port))
ssl_socket.send("data_string".encode())
# returns '4' (number of returned bytes)
ssl_socket.setblocking(0) # turn off blocking
ssl_socket.recv(4096)
# error: ssl.SSLWantReadError: The operation did not complete (read) (_ssl.c:1960)

如果我不将阻止设置为 0,它就会挂起。我已经做了足够的研究,发现它与 returned 数据的大小有关,但我在调用 ssl_socket.send() 时得到了 4 个字节的 return 值,所以我不确定我错过了什么。

请注意,我有一个 perl 客户端可以正常工作,如下所示:

#!/usr/bin/env perl

use IO::Socket::INET;
use IO::Socket::SSL;

# auto-flush on socket
$| = 1;

# create a connecting socket
my $socket = new IO::Socket::SSL (
    PeerHost => 'hostname',
    PeerPort => '12345',
    Proto => 'tcp',
    SSL_cert_file => $ENV{'HOME'} . '/path/to/client.pem',
    SSL_key_file => $ENV{'HOME'} . '/path/to/server.pem',
);
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";

# data to send to a server
my $req = 'data';
print $socket "$req\n";
my @r = ( <$socket> ) ;
print "@r";

$socket->close();

输出:

connected to the server
{
   "password": "passwd",
   "username": "username"
}

使用 Python SSL 库检索我请求的数据的正确方法是什么?

答案:我的数据字符串末尾需要一个 '\n' 字符。