This commit is contained in:
sangge 2023-10-23 17:02:04 +08:00
commit 83b50056f6
3 changed files with 19 additions and 17 deletions

View File

@ -1,3 +1,3 @@
[settings]
server_address = "127.0.0.1:8000"
server_address = 10.20.127.226:8000
version = 1.0

View File

@ -314,22 +314,25 @@ def get_own_ip() -> str:
# get node list from central server
def get_node_list(count: int, server_addr: str):
url = "http://" + server_addr + "/server/send_nodes_list"
payload = {"count": count}
response = requests.post(url, json=payload)
url = "http://" + server_addr + "/server/send_nodes_list?count=" + str(count)
# payload = {"count": count}
# response = requests.post(url, json=payload)
response = requests.get(url)
# Checking the response
if response.status_code == 200:
print("Success get node list")
node_ip = response.text
node_ip = eval(node_ip)
print(node_ip)
# insert node ip to database
with sqlite3.connect("client.db") as db:
db.executemany(
"""
INSERT INTO node
nodeip
VALUE (?)
(nodeip)
VALUES (?)
""",
node_ip,
[(ip,) for ip in node_ip],
)
db.commit()
print("Success add node ip")
@ -347,4 +350,4 @@ local_ip = get_own_ip()
if __name__ == "__main__":
import uvicorn # pylint: disable=e0401
uvicorn.run("client:app", host="0.0.0.0", port=8003, reload="True")
uvicorn.run("client:app", host="0.0.0.0", port=8003, reload=True)

View File

@ -95,20 +95,20 @@ async def receive_heartbeat_internal():
while 1:
timeout = 70
# 删除超时的节点
cursor.execute("DELETE FROM nodes WHERE last_heartbeat < ?", (time.time() - timeout,))
conn.commit()
# cursor.execute("DELETE FROM nodes WHERE last_heartbeat < ?", (time.time() - timeout,))
# conn.commit()
await asyncio.sleep(timeout)
@app.get("/server/send_nodes_list")
async def send_nodes_list(count: int) -> JSONResponse:
async def send_nodes_list(count: int) -> list:
'''
中心服务器与客户端交互, 客户端发送所需节点个数, 中心服务器从数据库中顺序取出节点封装成json格式返回给客户端
中心服务器与客户端交互, 客户端发送所需节点个数, 中心服务器从数据库中顺序取出节点封装成list格式返回给客户端
params:
count: 所需节点个数
return:
JSONResponse: {id: ip,...}
nodes_list: list
'''
nodes_list = {}
nodes_list = []
# 查询数据库中的节点数据
cursor.execute("SELECT * FROM nodes LIMIT ?", (count,))
@ -116,10 +116,9 @@ async def send_nodes_list(count: int) -> JSONResponse:
for row in rows:
id, ip, last_heartbeat = row
nodes_list[id] = ip
nodes_list.append(ip)
json_result = jsonable_encoder(nodes_list)
return JSONResponse(content=json_result)
return nodes_list
@app.get("/server/clear_database")
async def clear_database() -> None: