[Tutor] Trouble with sockets...

Modulok modulok at gmail.com
Thu Jun 17 11:25:57 CEST 2010


List,

I'm new to sockets and having trouble. I tried to write a simple
client/server program (see code below). The client would send a string
to the server. The server would echo that back to the client.

PROBLEM:
I can send data to the server, and get data back, but only for the
first call to the 'sendall()' method. If I try to call it in a loop on
the client, to print a count-down, only the first call gets echoed.
Clearly, I'm missing something.

EXAMPLE: (They're on the same physical machine.)
Shell on the server:
    Modulok at modUnix> ./socket_server.py
    Listening for clients...
    Got connection from 192.168.1.1

Shell on the client:
    Modulok at modUnix> ./latency_client.py 192.168.1.1 2554
    0

What I wanted:
    [-]Modulok at modUnix> ./latency_client.py 192.168.1.1 2554
    0
    1
    2


CODE:
################################
# The client program:
################################
import socket
import sys
def main():
    '''Send data to a server and receive the data echoed back to us.'''

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect( ('192.168.1.1', 2554) )

    for i in range(3):
        s.sendall(str(i))
        print s.recv(1024)
    s.close()

# Execution starts here:
try:
    main()
except KeyboardInterrupt:
    sys.exit("Aborting.")

################################
# The server program:
################################
import socket
import sys
def main():
    '''Listen for a client and echo data back to them.'''

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind( ('192.168.1.1', 2554) )
    s.listen(5)

    print "Listening for clients..."
    while True:
        channel, client = s.accept()
        print "Got connection from %s" % client[0]
        message = channel.recv(1024)
        channel.send(message)
        channel.close()

# Execution starts here:
try:
    main()
except KeyboardInterrupt:
    sys.exit("Aborting.")


More information about the Tutor mailing list