首页 > 解决方案 > Docker 套接字和 Python

问题描述

我试图让这个简单的 python3 代码使用套接字在 docker 中运行,但我收到以下错误。有人可以指出我正确的方向。我只是想让它工作,这样我就可以将它整合到我更广泛的项目中

File "registrar.py", line 29, in <module>
  with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
AttributeError: __exit__

服务器

import socketserver
import json

list_of_nodes = []
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):
        global list_of_nodes
        # 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(json.loads(self.data))
        # just send back the same data, but upper-cased
        list_of_nodes.append(json.loads(self.data))
        self.request.sendall(bytes(str(len(list_of_nodes)-1), 'utf-8'))
        print(list_of_nodes)


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

    # 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
import time
import json


HOST, PORT = "localhost", 58333
data = " ".join(sys.argv[1:])
dict_node = {'nVersion': 1,
             'nTime': time.time(),
             'addrMe': socket.gethostbyname(socket.gethostname())
             }

# 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))
    json_msg = json.dumps(dict_node)
    sock.sendall(bytes(json_msg, "utf-8"))

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

print("Sent:     {}".format(json_msg))
print("Received: {}".format(json.loads(received)))

标签: pythonpython-3.xdockersockets

解决方案


推荐阅读