Socket receiving in while 1
Question: I'm trying to create socket connections in python. I need to listen to server
until it sends a message, thus I need to use `while True`. Client:

    
    
    import RPi.GPIO as GPIO
    import time
    import socket
    
    GPIO.setmode(GPIO.BOARD)
    
    pinLDR = 7
    pinLED = 11
    touch = False
    sock = socket.socket()
    sock.connect(('192.168.1.67', 9092))
    
    while True:
        print sock.recv(256)
    
    def rc_time ():
        count = 0
    
        GPIO.setup(pinLDR, GPIO.OUT)
        GPIO.output(pinLDR, GPIO.LOW)
        time.sleep(0.1)
    
        GPIO.setup(pinLDR, GPIO.IN)
    
        while (GPIO.input(pinLDR) == GPIO.LOW):
        count += 1
    
        return count
    
    def led(lh):
        GPIO.setup(pinLED, GPIO.OUT)
        if lh == 1:
            GPIO.output(pinLED, GPIO.HIGH)
        else:
            GPIO.output(pinLED, GPIO.LOW)
    
    try:
        while True:
            print(str(rc_time()))
            if rc_time() > 5000:
                if touch == False:
                    print "triggered"
                    sock.send("triggered")
                    touch = True
            else:
                if touch == True:
                    sock.send("nottriggered")
                    print "nottriggered"
                    touch = False
    except KeyboardInterrupt:
        pass
    finally:
        GPIO.cleanup()
    sock.close()
    

But I have a problem with it. Nothing is printed even if a server sends a
message. And the whole code after first `while True` doesn't work


Answer: **UPDATE** : The issue with the code in the question is that it has an
infinite loop at the top. None of the code below this will ever execute:

    
    
    while True:
        print sock.recv(256)
    

(And apparently this particular server doesn't send a message until it's
received one first, so it will never send anything.)

* * *

Here's a simple working example. If this doesn't help, you'll need to provide
more context in your question.

Here's the client:

    
    
    import socket
    s = socket.socket()
    s.connect(('localhost', 12345))
    while True:
        print s.recv(256)
    

Corresponding server code:

    
    
    import socket
    import time
    
    s = socket.socket()
    s.bind(('', 12345))
    s.listen(0)
    conn, addr = s.accept()
    while True:
        conn.send("Hello")
        time.sleep(10)
    

