Bidirectional Networking

Bryan Olson fakeaddress at nowhere.org
Fri Dec 12 22:51:13 EST 2008


Emanuele D'Arrigo wrote:
> All the examples though are based on a client interrogating a server,
> with the client initiating the connection, obtaining something and
> then closing the connection. Basically the server is a reactive party:
> only if the client get in touch the server respond.

Indeed, to the network programmer that pattern of interaction defines 
client/server (according to Douglas Comer's /Internetworking with TCP/IP).

> What if the server
> wanted to notify the client of something of interest, i.e. new data
> that the client should take into consideration and potentially
> process?

The "server push" problem.

> One option would be for the client to periodically poll the server for
> changes. Fair enough, that would work. But it'd be a bit of a waste if
> the changes aren't particularly frequent.

Implementing server push on top of client poll is the most popular and 
generally simplest option.

> Is it possible then to establish both a server and a client in the
> same application?

Possible, and not all that hard to program, but there's a gotcha. 
Firewalls, including home routers and software firewalls, typically 
default to disallowing connections in the 'wrong' direction. If the 
client initiates all connections, you avoid a world of hassles.

> I guess it must be possible but the examples all
> rely on some kind of server loop (i.e. SocketServer.serve_forever)
> that if started on both client and server sides would create two
> listening parties but no talking at all! Furthermore, other libraries
> might have their own loop, i.e. a graphical client has a loop to
> redraw the screen and the two loops would somehow have to be
> interleaved.
> 
> I'm not quite seeing how this can be done other than we threads. Is
> that the way to do it? Place the listening loop in a thread while the
> rest of the application does its own thing?

Threads work. Other options in Python standard library are 'select' and 
'asyncore', but these do not play well with SocketServer and its 
descendants. There are also other free Python libraries.

> Or is it SocketServer.handle_request() the key? I could call this
> function periodically, but what happens if a request is made while the
> application is doing something else? Are the requests queued and dealt
> with one per loop?

Requests are queued up, but the queue is small. SocketServer is built on 
top of 'socket', which has the list() and accept() calls to create the 
queue and get connections from it, respectively. The traditional listen 
queue size, and sometimes the system maximum, is 5.

If you want to use SocketServer, read about ThreadingMixIn and ForkingMixIn.


-- 
--Bryan



More information about the Python-list mailing list