Python套接字:AttributeError:__exit __

问题描述 投票:2回答:1

我尝试从以下示例运行示例: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 python-2.7 sockets
1个回答
0
投票

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

在版本3.6中更改:对上下文管理器协议的支持为添加。退出上下文管理器等效于调用server_close()。

如果您不想升级,应该可以通过删除with语句并添加server_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()
© www.soinside.com 2019 - 2024. All rights reserved.