python: loop with socket.recv()

SagittariusA picture SagittariusA · Feb 13, 2013 · Viewed 16k times · Source

Do you know why this loop doesn't break?

#!/usr/bin/env python

from socket import *
import os
import sys

if __name__ == '__main__':
 HOST = '127.0.0.1'
 PORT = 55554

 print 'Creating socket'
 socketProxy = socket(AF_INET, SOCK_STREAM)

 print 'bind()'
 socketProxy.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
 socketProxy.bind((HOST, PORT))

 print 'Waiting for connection request'
 socketProxy.listen(1)
 conn, addr = socketProxy.accept()

 print 'Connected to ', addr

 request = ''

 while True:
    data = conn.recv(16);
    if not data: break
    request = request+data


print request
sys.stdout.flush()

I am writing a little Server-Proxy getting requests that can be arbitrary long so I must wait until I have received all the request. Anyway this loop (when len(data) == 0) doesn't stop and it keeps on waiting. How Can I stop it? Thanks

Answer

Some programmer dude picture Some programmer dude · Feb 13, 2013

One solution is to make the socket non-blocking. Then you receive in a loop until no more data is received. If no data has been received (i.e. request is empty) then the connection has been closed, otherwise you have your request.

When you have your request, send it on to the actual server, and do the same as above when waiting for the reply. Send the reply on to the client.