gpt4 book ai didi

Python 套接字 : AttributeError: __exit__

转载 作者:行者123 更新时间:2023-12-03 11:50:02 28 4
gpt4 key购买 nike

我尝试从以下位置运行示例:https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example
在我的笔记本电脑中,但它不起作用。

服务器 :

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())

if __name__ == "__main__":
HOST, PORT = "localhost", 9999

# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

客户 :
import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))

# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")

print("Sent: {}".format(data))
print("Received: {}".format(received))

此错误显示在客户端和服务器站点上:
Traceback (most recent call last):
File "C:\Users\Win7_Lab\Desktop\testcl.py", line 8, in <module>
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
AttributeError: __exit__
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\testcl.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]

最佳答案

看起来您尝试运行的示例是针对 Python 3 的,而您正在运行的版本是 Python 2.7。特别是,在 Python 3.2 中添加了对使用上下文管理器(即 with socket.socket())的支持.

Changed in version 3.2: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling close().



如果您不想升级,您应该能够通过删除 with 来修改您的代码。声明和调用 close() ,也许使用 try陈述:
try:
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
except:
pass
finally:
server.close()

相关 this question .

关于Python 套接字 : AttributeError: __exit__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49472282/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com