[Tutor] Python and sockets

Marilyn Davis marilyn at deliberate.com
Wed Aug 18 04:53:01 CEST 2004


For compare and contrast, here's my open_socket method.  Well, I'm
still developing on it but I think it might be pretty well-behaved by
now.

I talk directly to _socket and skip the socket class layer.  I'm
setting up to be a pop email client here.  I also skip the poplib
layer of stuff.  Those libraries introduced some inefficiencies and
obscurations for my particular task.

However, my code borrows heavily from those libraries.  In fact,
studying the code for any of the libraries that work through a socket
can be quite instructive: telnet, poplib, socket, ... what else?

Hope it helps,

Marilyn Davis



import _socket


     def open_socket(self, port = 110):
         if log.level & log.pop:
             log.it("Host = " + self.host + " port = " + str(port))
         possibles = _socket.getaddrinfo(self.host, port, 0, _socket.SOCK_STREAM)
         for res in possibles:
             af, socktype, proto, canonname, sa = res
             try:
                 if log.level & log.verbose:
                     log.it("Trying (" + str(af) + ', ' + str(socktype) + ', ' + str(proto) + ')')
                 self.remote = _socket.socket(af, socktype, proto)
                 if log.level & log.verbose:
                     log.it("Connecting to " + str(sa))
                 self.remote.connect(sa)
             except _socket.error, msg:
                 if log.level & log.verbose:
                     log.it("Failed , _socket.error: " + str(msg) )
                 if self.remote:
                     if log.level & log.verbose:
                         log.it("Couldn't connect to " + str(sa) + ".  Closing.")
                     self.remote.close()
                     self.remote = None
                 continue
             break
         if not self.remote:
             self.host_down("Could not open a socket to host = " + self.host + " port = " + str(port))
         welcome = self.remote.recv(RESPONSE_BLOCK)
         if log.level & log.verbose:
             log.it("Welcome: " + welcome)





More information about the Tutor mailing list