python-3.x - Python SSL 套接字错误 : ssl. SSLWantReadError: The operation did not complete (read)

标签 python-3.x sockets ssl blocking recv

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

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,它就会挂起。我已经做了足够的研究,发现它与返回数据的大小有关,但我在调用 ssl_socket.send() 时得到了 4 个字节的返回值,所以我不确定我错过了什么。

请注意,我有一个 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' 字符。

关于python-3.x - Python SSL 套接字错误 : ssl. SSLWantReadError: The operation did not complete (read),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006850/

相关文章:

c++ - 可能是 boost ssl 握手函数有一些内存泄漏

python - 不同网络上的 UDP 组播

python - 当尝试打破 Python 3 中的 "receive"循环时,服务器套接字应用程序变成无限循环

Java套接字客户端到不同网络上的服务器。

security - 计算机是否部署了预先计算的素数列表

apache - 在 Apache 反向代理后面使用 SSL 的 JIRA 服务器无法正常工作

Python:for循环在print()中

python - 在 Python 中使用 bool 值进行索引如何工作?

python - selenium webriverwait 引发错误但没有描述

Python 随机从列表中选择没有先前的选择