[Tutor] sockets

Brendon bren@europe.nl.com
Wed, 4 Jul 2001 12:56:11 +0200


On Thursday 01 January 1970 00:59, you wrote:
> On Mon, 2 Jul 2001, Danny Yoo wrote:
> > > s.close()
> > > print 'Received', data
> > > #-------------------------
> > >
> > > the statement "data = s.recv(1024)" apparently causes the first 1024
> > > characters to be assigned to 'data', but because eventually it'll go
> > > over the limit i want it to write every packet to a file which can be
> > > queried later.
> >
> > You can do the s.recv() in a loop that keeps on pulling data from the
> > socket, until the socket runs dry.
> >
> > ###
> > whole_data = ''
> > while 1:
> >     data = s.recv(1024)
> >     if not data: break
> >     whole_data += data
> > ###
>
> Err... that is, until the socket blocks.  *sigh*  I just tried the
> example, and the program stalls after one iteration of the loop.  The
> problem lies on this line:
>
>      data = s.recv(1024)
>
> If the server doesn't have anything to send, but if we don't want to
> terminate the connection, we'll twiddle our fingers and wait.  In a sense,
> we'l
> l "block" until the server starts sending us something interesting.
> (The same sort of behavior is responsible for what allows raw_input() to
> "pause" the system: the system is waiting for input from us, and is
> essentially "blocked".)
>
> What you'll probably want to look at is a way of asking the socket: "if
> there's anything interesting coming at us from the server, tell us about
> it.  But if not, let me do my own thing."  I think this is asynchronous
> io, but I've never actually played with async stuff before.  You might
> want to look at:
>
>     http://python.org/doc/lib/module-asyncore.html
>
> which seems to have some good documentation on doing asyncronous IO.
> I'll need to take a look at the Stevens book myself, one of these days, to
> understand what's happening.

hmm, but.. what i want to happen is when data arrives, it gets thrown into a 
file where it is validated and parsed after which the socket waits for data 
again.

so how do IM clients (and, actually.. just about everything that operates 
with a network connection) do this then? threading i'm guessing but i once 
heard mentioned that it wasn't ideal.

basically, what needs to be done is have a socket that keepson receiving data 
while the rest of the program does it's thing. i.e. parse that data and 
handle UI events.

from http://www.nightmare.com/pythonwin/async_sockets.html:

"What is 'asynchronous socket programming'? 

a.k.a. event-driven programming or select()-based multiplexing, it's a 
solution to a network programming problem: How do I talk to bunch of
different network connections at once, all within one process/thread?"

which isn't what i'm looking for, i think (?).

--
"if we live by an "eye for an eye and a tooth for a tooth"...before long, 
the whole world will be blind and toothless." 
         --Tevye, Fiddler on the Roof