Socket reading script - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Networking (https://python-forum.io/forum-12.html) +--- Thread: Socket reading script (/thread-17587.html) |
Socket reading script - Will86 - Apr-17-2019 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: breakoutput is like : Quote:Status 1 where the device is only changing status 3 times, I should have : Quote:Status 1 Any idea of what socket module I should use to avoid that? Alternatively, is there any better way to do this? RE: Socket reading script - Gribouillis - Apr-17-2019 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. RE: Socket reading script - Will86 - Apr-17-2019 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 RE: Socket reading script - Gribouillis - Apr-17-2019 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()
RE: Socket reading script - Will86 - Apr-17-2019 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 |