network programming: how does s.accept() work?

7stud bbxx789_05ss at yahoo.com
Mon Feb 25 03:51:10 EST 2008


I have the following two identical clients

#test1.py:-----------
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 5052  #server port

s.connect((host, port))
print s.getsockname()

response = []
while 1:
    piece = s.recv(1024)
    if piece == '':
        break

    response.append(piece)


#test3.py:----------------
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = 'localhost'
port = 5052  #server port

s.connect((host, port))
print s.getsockname()

response = []
while 1:
    piece = s.recv(1024)
    if piece == '':
        break

    response.append(piece)


and this basic server:

#test2.py:--------------
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = ''
port = 5052

s.bind((host, port))
s.listen(5)


while 1:
    newsock, client_addr = s.accept()
    print "orignal socket:", s.getsockname()

    print "new socket:", newsock.getsockname()
    print "new socket:", newsock.getpeername()
    print


I started the server, and then I started the clients one by one.  I
expected both clients to hang since they don't get notified that the
server is done sending data, and I expected the server output to show
that accept() created two new sockets.  But this is the output I got
from the server:

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5052)
new socket, peer: ('127.0.0.1', 50816)

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5052)
new socket, peer: ('127.0.0.1', 50818)

The first client I started generated this output:

('127.0.0.1', 50816)

And when I ran the second client, the first client disconnected, and
the second client produced this output:

('127.0.0.1', 50818)

and then the second client hung.  I expected the server output to be
something like this:

original socket: ('127.0.0.1', 5052)
new socket, self: ('127.0.0.1', 5053)
new socket, peer: ('127.0.0.1', 50816)

original socket: ('0.0.0.0', 5052)
new socket, self: ('127.0.0.1', 5054)
new socket, peer: ('127.0.0.1', 50818)

And I expected both clients to hang.  Can someone explain how accept()
works?



More information about the Python-list mailing list