python - 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)))
解决方案
推荐阅读
- ionic-framework - how to navigate to specific tabs index from other page(dont have tab originally) in ionic 3?
- ios - Flutter 应用程序的音频无法通过扬声器工作
- node.js - 重新连接后待处理的猫鼬查询
- java - java htmlunit在单击页面的提交按钮时抛出ScriptException
- excel - office-js customTab 和工作表可见性在 excel 64 位中不起作用
- c# - 我希望除 UWP 中的“LoginPage”之外的所有页面都可以访问“SplitViewRoot”,如何使其工作?
- angular - 跨域请求被阻止——使用 Angular 和 ASP.NET Core 构建的应用程序
- javascript - JS:JSON 检索所有 JSON 数据
- git - 我如何查看 git 项目的扩展在哪里?
- sbt - 如何访问像 assemblyJarName 这样的 sbt 变量的值?