2

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.

Mike111177
  • 25
  • 1
  • 5
  • is it `string.split` or `str.split`? because i do not see an import or a `str` identifier. – Don Question Mar 18 '15 at 00:00
  • 1
    `str.split('hello\nworld', '\n')` is fine, if a little unconventional - just calling the unbound method of the `str` builtin as opposed to the bound method of the `'hello\nworld'` object. – Tris Forster Mar 18 '15 at 00:17
  • Note that you can't always detect (abrupt) disconnections without writing unless you're willing to use keep-alive (or time out). That's quite general regarding TCP, independently of the language (see [links from this answer](http://stackoverflow.com/a/6404085/372643)). – Bruno Mar 18 '15 at 00:17

1 Answers1

2

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")
  ...
Tris Forster
  • 152
  • 4