Reputation: 25
Ok, I have a socket and I'm handling one line at a time and logging it. The code below works great for that. The cout function is what I use to send data to the log. The for loop I use so I can process one line at a time.
socket.connect((host, port))
readbuffer = ""
while True:
readbuffer = readbuffer+socket.recv(4096).decode("UTF-8")
cout("RECEIVING: " + readbuffer) #Logs the buffer
temp = str.split(readbuffer, "\n")
readbuffer=temp.pop( )
for line in temp:
#Handle one line at a time.
The I ran into a problem where when the server disconnected me, all of the sudden I had a massive file full of the word "RECEIVING: ". I know this is because when a python socket disconnects the socket starts receiving blank data constantly.
I have tried inserting:
if "" == readbuffer:
print("It disconnected!")
break
All that did was immediately break the loop, and say that it disconnected, even on a successful connection.
I also know that I can detect a disconnection by sending data, but I can't do that, because anything I send gets broadcasted to all the other clients on the server, and this is meant to debug those clients so I it would interfere.
What do I do. Thank you in advanced.
Upvotes: 2
Views: 3808
Reputation: 162
You need to check the result of the recv()
separately to the readbuffer
while True:
c = socket.recv(4096)
if c == '': break # no more data
readbuffer = readbuffer + c.decode("UTF-8")
...
Upvotes: 2