Subclassing socket

Maksim Kasimov maksim.kasimov at gmail.com
Wed Dec 21 02:42:12 EST 2005


you have to agregate socket and the object must have "fileno" method,
thats gives a possibility to use instanses of your class with "select.select" function


class mySocket:

     def __init__(self, ...):
         self.__socket = None
	...


     def fileno(self):
         return self.__socket.fileno()


     def connect(self, __host, __port):
         try:
             self.close()
             self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             self.__socket.connect((__host, __port))
	    ...


     def close(self):
         try:
             if self.__socket is not None:
                 self.__socket.close()
         finally:
             self.__socket = None

     ...


groups.20.thebriguy at spamgourmet.com wrote:
> socket objects have a little quirk.  If you try to receive 0 bytes on a
> blocking socket, they block.  That is, if I call recv(0), it blocks
> (until some data arrives).
> 
> I think that's wrong, but I don't want to argue that.  I would like to
> create a subclass of socket that fixes the problem.  Ideally, something
> like:
> 
> class new_socket(socket):
>     def recv( self, bufsize, flags=0 ):
>         if bufsize == 0:
>             return ""
>         else:
>             return socket.recv( bufsize, flags )
> 
> They only problem is, sockets return socket objects via the accept
> call.  And the socket returned is of type socket, of course, not
> new_socket, as I would like.  I could override accept() to return a
> new_socket, but I don't know how to convert the old socket to a new
> socket.  That is, I'd like to add a method to the class above something
> like:
> 
>     def accept( self ):
>         conn, addr = socket.accept()
>         <convert conn, which is type socket to type new_socket>
>         return ( conn, addr )
> 
> Does anyone have any suggestions on how to do the above?
> 


-- 
Best regards,
Maksim Kasimov
mailto: maksim.kasimov at gmail.com



More information about the Python-list mailing list