Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket reading script
#1
Hello all,

I am writing a script to know the status of a networked device. A small API allow minimum integration.
My script is basically opening a socket and buffering the data from this socket in a while loop.
It seems that each time the loop is going on, I read the same data via s.recv(1024) and therefore duplicate my output.

Is there another method to avoid this?

Extract of my code
import socket
import time

def run(self):
        def timer(host,T,Fmax,ms1):
            ms1=self.ms1
            s.settimeout(T)
            F=1
            while True: #Ctrl+C to interrupt the loop
                time.sleep(0.5)
                try:
                    data=s.recv(1024)
                    data=data.decode()
                    data=data.strip()
                except socket.timeout:
                    F+=1
                    if F==Fmax or F>Fmax:
                        break
output is like :
Quote:Status 1
Status 1
Status 1
Status 1
Status 2
Status 2
Status 3

where the device is only changing status 3 times, I should have :
Quote:Status 1
Status 2
Status 3

Any idea of what socket module I should use to avoid that? Alternatively, is there any better way to do this?
Reply
#2
How could we help if you post incomplete code that doesn't do anything? It is impossible for the above code to produce the described output. The code doesn't even print anything.
Reply
#3
Sorry, my code is rather long and inelegant.

I tried to only extract what was useful in the above, below is the entire work in progress :

Long and inelegant code
Reply
#4
Quote:It seems that each time the loop is going on, I read the same data via s.recv(1024)
This cannot happen. Your script potentially starts several threads, each of them opening a new socket. Could it be that the multiple outputs are written by different threads? Try to print the thread's ID together with the output. You can use threading.get_ident()
Reply
#5
I already identify each thread via self.ms1 - I have one device per thread and all devices are stored on my JSON library
When I delete all but one device my JSON library, I end up with the same result...

I have solved it by breaking the while with a continue as below :
                    data=""
                    data2=s.recv(1024)
                    if data==data2:
                        continue

                    data=data2.decode()
                    data=data.strip()
Not really elegant, but seems to work. Thanks @Gribouillis
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020