Python Socket SSL OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (wh

Python Socket SSL OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (wh

完整错误代码:

Traceback (most recent call last):
  File "C:\path\to\my\python\code\server_ssl_testing.py", line 15, in <module>
    response = ssock.recv(1024).decode("utf-8")
  File "C:\Program Files\Python39\lib\ssl.py", line 1228, in recv
    return super().recv(buflen, flags)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

我创建了 SSL 套接字服务器和客户端,但随后服务器尝试从客户端接收信息失败并打印出此文本上方的错误。

服务器:

import socket
import ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('certs/server-cert.pem', 'certs/server.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('localhost', 2642))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        response = ssock.recv(1024).decode("utf-8")
        print(response)

客户:

import socket
import ssl

hostname = 'localhost'
context = ssl.create_default_context()

sock = socket.create_connection((hostname, 2642))
ssock = context.wrap_socket(sock, server_hostname=hostname)
msg = "Hello World!"
ssock.send(msg.encode("utf-8"))

在server.py中我应该写conn.recv而不是ssock.recv。 如果将来有人想这样做,应该会有所帮助 =)