[Edu-sig] Python Network Programming

Seabrook, Richard rhseabrook at aacc.edu
Sun Oct 24 19:11:38 CEST 2004


In John Goerzen's new text "Foundations of Python Network Programming" I 
had difficulty getting the Chapter 1 client and server examples to use the
file socket interface correctly under Linux Fedora Core 1 using Python 2.3.  The problem seems to be the "rw" mode since the workaround
is to open separate files for read and write.  The commented lines below
are where I tried the sock.recv() and sock.send() calls to make sure the socket itself was working correctly.  Here's the modified code:

[dick at grundoon Networks]$ cat server2.py
#!/usr/bin/env python
# Simple Server - Chapter 1 - server.py
import socket

host=''         # Bind to all interfaces
port = 51423

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)

print "Server is running on port %d; press Ctrl-C to terminate." % port

while 1:
        clientsock, clientaddr = s.accept()
        clientrfile = clientsock.makefile('r')
        clientwfile = clientsock.makefile('w')
        clientwfile.write("Welcome, " + str(clientaddr) + "\n")
#       clientsock.send("Welcome, " + str(clientaddr) + "\n")
        clientwfile.write("Please enter a string: ")
#       clientsock.send("Please enter a string: ")
        line = clientrfile.readline().strip()
#       line = clientsock.recv(2048).strip()
        clientwfile.write("You entered %d characters.\n" % len(line))
#       clientsock.send("You entered %d characters.\n" % len(line))
        clientrfile.close()
        clientwfile.close()
        clientsock.close()

=======================================================================
Dick S.



More information about the Edu-sig mailing list