Python Socket:AttributeError:__ exit__

时间:2018-03-25 03:35:47

标签: python python-2.7 sockets

我尝试从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\]

1 个答案:

答案 0 :(得分:0)

看起来您要运行的示例是针对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有关。