0

I am trying to connect two nodes via WebSocket API but I have trouble letting the kern object do the API call. And I am also trying to let the node to node communication work in another thread. Or should I just discard oop? I think without oop everything should work just fine. I am new to python. Any ideas?

Here is my code

import boto3
import os
import requests
from botocore.handlers import disable_signing
import asyncio
import websockets
from botocore.exceptions import ClientError
import logging
from azure.storage.blob import BlobServiceClient
from flask import Flask, request
import time
import threading



ID = "xxxx"
device_name="node1"
loop=0



app = Flask(__name__)
# @app.route('/post', methods=['POST'])
class Kern:
    def __init__(self):
        self.leader=0
        self.loop=0

    def download_blob_to_file(self,blob_service_client: BlobServiceClient, container_name, bolb):
        blob_client = blob_service_client.get_blob_client(container=container_name, blob=bolb)
        with open(file=os.path.join('/home/tian0138/csci-5105/Research', bolb), mode="wb") as sample_blob:
            download_stream = blob_client.download_blob()
            sample_blob.write(download_stream.readall())
    def handle_post_request(self,response):
        # Get the data from the request body
        ID = response["ID"]
        container = response["container"]
        bolb = response["bolb"]
        account_name = response["account_name"]
        account_url = "https://{}.blob.core.windows.net".format(account_name)
        blob_service_client = BlobServiceClient(account_url=account_url)
        self.download_blob_to_file(blob_service_client,container,bolb)
        # Process the data...
        return 'Success'

    def boot(self):
        url = 'http://localhost:8000/post'
        data = {"ID": ID, "device_name": device_name}
        response = requests.post(url, data=data)
        response = response.json()
        print(response)
        self.handle_post_request(response)

    async def node_heartbeat_response(self,websocket):
        async for message in websocket:
            components=message.split('!')
            if len(components)==1:#ping
                ping=components[0]
                print(ping)
                response="pong"
            else:
                response="wrong"
            expiration=500
            await websocket.send(response)

    async def node_heartbeat(self):#leader send 
        time.sleep(2)
        async with websockets.connect("ws://localhost:8765",ping_interval=None) as websocket:
            await websocket.send("ping") 
            result = await websocket.recv()
            print(result)

    async def connect_follower_heart(self):# 
        async with websockets.serve(self.node_heartbeat_response, "localhost", 8765,ping_interval=None):
            await asyncio.Future()  # run forever

k1=Kern()
k1.boot()
decision = input("Leader?")
if decision=="leader":
    print("in leader")
    k1.leader=1
    leader_heartbeat = threading.Thread(target=k1.asyncio.run(node_heartbeat))
    leader_heartbeat.start()
else:
    follower_thread = threading.Thread(target=k1.asyncio.run(connect_follower_heart))
    follower_thread.start()
while True:
    k1.loop=k1.loop+1
leader_heartbeat.join()
follower_thread.join()

I didn't similar usage or should I try another way?

2
  • k1 is an instance of Kern, which has no asyncio attribute at all. Did you mean to call asyncio.run(k1.node_heartbeat)? There are also likely issues with running async tasks in threads (1, 2), but that's a separate issue. Commented Apr 20, 2023 at 21:19
  • Could it be that the while loop never breaks? It seems to me that you'll get stuck doing k1.loop = k1.loop + 1 and never get to the joins. Also, what are you trying to do at a higher level? This seems like very complicated code if you're new to Python, there is probably a simpler way of achieving whatever you're trying to achieve! Commented Apr 22, 2023 at 12:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.