Why do I have to restart the tcp_server program once it receives the data?
Question: I'm using a simple tcp_server in python. Here is the code:-

    
    
    import socket
    
    TCP_IP = '127.0.0.1'
    TCP_PORT = 5005
    BUFFER_SIZE = 1024
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    s.listen(1)
    
    conn, addr = s.accept()
    #inputs = [conn, serial_obj]
    outputs = []
    #read_input.read_input(inputs,outputs)
    while 1:
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        print "received data:", data
        conn.send(data)
    
    conn.close()
    

My question is once it receives the data, the connection is dropped and I have
to re-run the tcp_server program to initiate the connection. How do I keep it
listening forever.


Answer: You need two nested while loops. The outer loop runs forever, once per
incoming connection. The inner loop runs according to the data it receives on
the current connection. Try this:

    
    
    import socket
    
    TCP_IP = '127.0.0.1'
    TCP_PORT = 5005
    BUFFER_SIZE = 1024
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    s.listen(1)
    
    while True:
        conn, addr = s.accept()
        #inputs = [conn, serial_obj]
        outputs = []
        #read_input.read_input(inputs,outputs)
        while 1:
            data = conn.recv(BUFFER_SIZE)
            if not data: break
            print "received data:", data
            conn.send(data)
        conn.close()
    

