The Python Oracle

Python sockets - keep socket alive?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
01:07 Accepted answer (Score 9)
02:14 Answer 2 (Score 3)
03:24 Thank you

--

Full question
https://stackoverflow.com/questions/5110...

Answer 1 links:
http://docs.python.org/library/select.ht...
http://docs.python.org/library/multiproc...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sockets #tcp #client

#avk47



ACCEPTED ANSWER

Score 10


If a client closes a connection, you want it to close the socket.

It seems like there's a bit of a disconnect here that I'll try to elaborate on. When you create a socket, bind, and listen, you've established an open door for others to come and make connections to you.

Once a client connects to you, and you use the accept() call to accept the connection and get a new socket (conn), which is returned for you to interact with the client. Your original listening socket is still there and active, and you can still use it to accept more new connections.

Looking at your code, you probably want to do something like this:

while True:
    print("Now listening...\n")
    conn, addr = s.accept()

    print 'New connection from %s:%d' % (addr[0], addr[1])
    data = conn.recv(socksize)
    if not data:
        break
    elif data == 'killsrv':
        conn.close()
        sys.exit()
    else:
        print(data)

Please note that this is just a starting point, and as others have suggested you probably want to use select() along with forking off processes or spawning threads to service each client.




ANSWER 2

Score 3


Your code is only accepting a single connection - the loop only deals with the first accepted connection and terminates as soon as it lost. This is way your server exists:

data = conn.recv(socksize)
if not data:
    break

What you will need to do is to accept several connections, while handling each of those in it's own loop. Note that it does not have to be a real loop for each socket, you can use a select-based approach to query which of the sockets has an event associated with it (data available, connection lost etc.) and then process only those sockets, all in the same loop.

You can also use a multi threaded / multi process approach, dealing with each client in it's own thread or process - I guess you won't run into scaling issues when playing around.

See:

http://docs.python.org/library/select.html

http://docs.python.org/library/multiprocessing.html