[Tutor] Trouble with sockets...
bob gailer
bgailer at gmail.com
Fri Jun 18 19:50:45 CEST 2010
On 6/17/2010 5:25 AM, Modulok wrote:
> 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()
>
Problem is you close the channel after one string is processed. That in
turn closes the client socket.
Either keep the channel open or put the client connect in the loop.
> # Execution starts here:
> try:
> main()
> except KeyboardInterrupt:
> sys.exit("Aborting.")
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list