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(sock et):
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? 10 5572
imho:
class new_socket(sock et):
def __init__(self, family=AF_INET, type=SOCK_STREA M, proto=0,
_sock=None)
socket.__init__ (self, family=AF_INET, type=SOCK_STREA M, proto=0,
_sock=None)
def accept( self ):
conn, addr = socket.accept()
return ( new_socket(_soc k=conn), addr )
but i think your problem have a more simple way then inheritance
you have to agregate socket and the object must have "fileno" method,
thats gives a possibility to use instanses of your class with "select.sel ect" function
class mySocket:
def __init__(self, ...):
self.__socket = None
...
def fileno(self):
return self.__socket.f ileno()
def connect(self, __host, __port):
try:
self.close()
self.__socket = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
self.__socket.c onnect((__host, __port))
...
def close(self):
try:
if self.__socket is not None:
self.__socket.c lose()
finally:
self.__socket = None
... gr************* ****@spamgourme t.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(sock et): 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: ma************@ gmail.com
More simple way? What's that? gr************* ****@spamgourme t.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).
Well, arguably you should just try to stop receiving zero bytes. Why on
earth is your application doing this?
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(sock et): def recv( self, bufsize, flags=0 ): if bufsize == 0: return "" else: return socket.recv( bufsize, flags )
That would indeed work, were it not for the complications you are about
to relate.
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?
You could use the "delegation " pattern - return an object that contains
a reference to the socket returned by accept(), and have that object
implement recv() as you outline above, and __getattr__() so that any
methods your socket *doesn't* implement are instead called on the socket
returned by accept().
There's a whole page of stuff at http://aspn.activestate.com/ASPN/sea...&y=0&type=ASPN
but the best read will probably be http://aspn.activestate.com/ASPN/Coo...n/Recipe/52295
In that article Alex talks about how old-style classes can't inherit
from basic Python types. This is out of date now for most types, but his
exposition of the principles of delegation remains a beacon of clarity.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
Steve,
To your question of why you'd ever receive value:
This is very common in any network programming. If you send a packet
of data that has a header and payload, and the header contains the
length (N) of the payload, then at some point you have to receive N
bytes. If N is zero, then you receive 0 bytes. Of course, you CAN
test for N == 0, that's obvious - but why would you if the underlying
layers worked correctly? Its just extra code to handle an special case.
Correction to my last post:
It should say:
"To your question of why you'd ever recv(0):" gr************* ****@spamgourme t.com wrote: To your question of why you'd ever [recv(0)].
This is very common in any network programming. If you send a packet of data that has a header and payload, and the header contains the length (N) of the payload, then at some point you have to receive N bytes. If N is zero, then you receive 0 bytes. Of course, you CAN test for N == 0, that's obvious - but why would you if the underlying layers worked correctly? Its just extra code to handle an special case.
We need "extra code" around recv to ensure we get exactly
N bytes; 'recv(N)' can return less. The most straightforward
code I know to read exactly N bytes never passes zero to
recv (untested):
def recvall(sock, size):
""" Read and return exactly 'size' bytes from socket 'sock'.
Kind of the other side of sock.sendall.
"""
parts = []
while size > 0:
data = sock.recv(size)
if not data:
raise SomeException(" Socket closed early.")
size -= len(data)
parts.append(da ta)
return ''.join(parts)
--
--Bryan
I don't think this is true in all cases - for example, if the protocol
is UDP, and the packet size is less than the MTU size. Although, I
could be wrong - I've always thought that to be the case.
I knew someone would have your response, that's why I earlier said I
didn't want to argue that. :-)
But thanks for your comments. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: WhiteRavenEye |
last post by:
Why can't I subclass any window except mine in VB?
Do I have to write dll for this?
I've tried to subclass it with SetWindowLong but without success...
Does anyone know how to subclass window ANY window in VB?
Thanks...
|
by: GrelEns |
last post by:
hello,
i wonder if this possible to subclass a list or a tuple and add more
attributes ? also does someone have a link to how well define is own
iterable object ?
what i was expecting was something like :
>>> t = Test('anAttributeValue', )
>>> t.anAttribute
|
by: David Vaughan |
last post by:
I'm using v2.3, and trying to write to text files, but with a maximum
line length. So, if a line is getting too long, a suitable ' '
character is replaced by a new line. I'm subclassing the file class,
and, as long as I just use the write method, this works fine. But
"print >>" doesn't behave as I want:
class max_width_file(file):
def...
|
by: BJörn Lindqvist |
last post by:
A problem I have occured recently is that I want to subclass builtin
types. Especially subclassing list is very troublesome to me. But I
can't find the right syntax to use. Take for example this class which
is supposed to be a representation of a genome:
class Genome(list):
def __init__(self):
list.__init__(self)
self =
....
|
by: Brent |
last post by:
I'd like to subclass the built-in str type. For example:
--
class MyString(str):
def __init__(self, txt, data):
super(MyString,self).__init__(txt)
self.data = data
| |
by: Christopher Benson-Manica |
last post by:
Sorry for the lame title, but it's hard to condense what I'm about to
say... Here's my situation (my first real C++ situation, yay!).
Currently we have a MyTCPThread (don't let the name scare you, this
isn't OT) that has a socket member object that has methods Send() and
GetLine() for sending and receiving data. I want to subclass...
|
by: mukappa |
last post by:
I found an earlier post about subclassing cElementTree.Element which
can't
be done because it is a factory method. I am trying to subclass
XMLTreeBuilder
with success using the python implementation, but not with
cElementTree.
$ python
Python 2.3.4 (#1, Feb 22 2005, 04:09:37)
on linux2
|
by: manatlan |
last post by:
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b",...
|
by: Ray |
last post by:
Hi all,
I am thinking of subclassing the standard string class so I can do
something like:
mystring str;
....
str.toLower ();
A quick search on this newsgroup has found messages by others
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |