1

I write the following code to receive data, then write the data to a file.

My question is: I found the if branch (" if not data: break ") never be executed, 1). Why does the if branch never be reached? 2). How my code can exit the while loop?

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/var/run/output.socket")

while True:
    data = s.recv(1024)
    if not data:
        break
    else:
        f = open("/home/ematt/test.log",'a')
        f.write(data)
Matt Elson
  • 4,177
  • 8
  • 31
  • 46

2 Answers2

0

socket.recv always has data. It will wait until some data arrives.

See https://docs.python.org/2/library/socket.html

xfx
  • 1,918
  • 1
  • 19
  • 25
0

socket.recv is a blocking call, it returns when data has been received (or the peer has closed the connection)

In case you want to avoid waiting on data to arrive, you can set the socket to non-blocking mode using

s.setblocking(False)

In such mode, recv throws an exception when no data is available. Please see this SO QA for more info and a code example on how to use it

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43