【问题标题】:Python Socket : AttributeError: __exit__Python 套接字:AttributeError:__exit__
【发布时间】:2018-03-25 03:35:46
【问题描述】:

我尝试从 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】:

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

在 3.2 版中更改:对上下文管理器协议的支持是 添加。退出上下文管理器相当于调用 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相关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2015-01-19
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多