Search code examples
pythonsocketsnodemcu

Combine Listener (POST request) and Reader (GET request) files client and host


I have two files in python for sending and receiving data to a nodemcu connected on local network.

Sender.py


import urllib.request
url = "http://Device IP"
# Example usage
while True:
    data = input("Enter Data:")
    data = urllib.parse.urlencode({"plain": data})
    data = data.encode('ascii')
    urllib.request.urlopen(url + "/SEND", data)

Listener.py


import urllib.request
url = "http://Device IP"
# Example usage
n = urllib.request.urlopen(url + "/LISTEN").read()
n = n.decode("utf-8")  # convert raw html bytes format to string

I run both scripts separately at the same time and they work fine. If some data is sent from board it shows in listener.py output And if I send data from sender.py it gets shown on board.

But I would like to combine these files so that if data is sent/received it doesn't interrupt with each other or place these in loop. Just like one would setup a mqtt broker or blynk (Will not be using these).

So what direction should I start looking. I have tried to get into socket programming on python but they also seem to create two files for client and host.(Atleast the ones I have found on internet)

So what would be the most adequate approach here.

Regarding the queries in comment

  1. By combining I can see the output and access data shared from both sides.

  2. By interrupt I mean for example when the python code is in sending mode it waits (pauses) the code on line input() If the board tries to send data during this time the python code won't be able to listen to it.


Solution

  • So currently I achieved the task using Threading. I am running both the main functions listener/sender on different threads and saving the data with global values.

    It ain't much but it's honest work.

    Maybe in feature, someone will find a better way.