Socket Help

Stewart Midwinter stewart at midwinter.ca
Tue Mar 30 04:36:08 CEST 2004


Lindstrom Greg - glinds <Greg.Lindstrom at acxiom.com> wrote in message news:<mailman.62.1080574302.20120.python-list at python.org>...


> I'd ask if there is a simple way to verify my socket is still communicating.

how about this, taken from a non-blocking socket class's Connect method:

class NBSocket:
    def __init__(self):
        self.__host = 'localhost'
        self.__port = 177
        self.__myconnection = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        self.__myconnection.setsockopt(0,socket.SO_KEEPALIVE,1)
        self.__connected = 0
        return

    def connect(self, host = 'localhost', port = 177, applicationName = 'NBSocket'):
        """
        ======================================================================c+
        NBSocket.connect(self,host,port,applicationName)
        
        This procedure opens the connection to the socket defined in __init__
        it takes the host name, prot number and application name as aruguments
        host defaults to localhost
        port defaults to 177
        application name defaults to None
        It tries to connect once and if it doesn't get a response after 5
        seconds or if it can't connect right away it raises a socket.error
        exception
        ======================================================================c-
        """
        # Test to see if we are already connected
        if self.__connected:
            print "This socket is already connected"
            return 1
        self.__host = host
        self.__port = int(port)
        self.__applicationName = applicationName
        counter = 0
        try:

            failed = 1
            while failed:
                try:
                    self.__myconnection.recv(1024)
                    self.__connected = 1
                    self.__myconnection.setblocking(1)
                    failed = 0
                    print 'connected'
                except socket.error:
                    print 'unable to connect'
                    counter = counter + 1
                    time.sleep(1)
                    if counter > 5:
                        raise
        except socket.error:
            raise

then continue on with your communication with the server...

cheers,
S



More information about the Python-list mailing list