Socket Programming HOWTO example

Bryan Olson fakeaddress at nowhere.org
Tue Jan 17 13:16:42 EST 2006


Marco Meoni wrote:
> Hi. I read the Gordon McMillan's "Socket Programming Howto".
> I tried to use the example in this howto but this doesn't work.

You are right, that obviously won't work. The code passes
'self' to __init__, but not to any of the others methods.

I'm cc'ing this post to gmcm at hypernet.com.


> The code is 
 > class mysocket:
>         '''classe solamente dimostrativa
>           - codificata per chiarezza, non per efficenza'''
>         def __init__(self, sock=None):
>             if sock is None:
>                 self.sock = socket.socket(
>                     socket.AF_INET, socket.SOCK_STREAM)
>             else:
>                 self.sock = sock
>         def connect(host, port):
>             self.sock.connect((host, port))
>         def mysend(msg):
>             totalsent = 0
>             while totalsent < MSGLEN:
>                 sent = self.sock.send(msg[totalsent:])
>                 if sent == 0:
>                     raise RuntimeError, \\
>                         "connessione socket interrotta"
>                 totalsent = totalsent + sent

To send exactly MSGLEN bytes, use socket's 'sendall' method.

>         def myreceive():
>             msg = ''
>             while len(msg) < MSGLEN:
>                 chunk = self.sock.recv(MSGLEN-len(msg))
>                 if chunk == '':
>                     raise RuntimeError, \\
>                         "connessione socket interrotta"
>                 msg = msg + chunk
>             return msg

> How can i use this?

Treat it as a "HowNotTo".


-- 
--Bryan



More information about the Python-list mailing list