[Tutor] asynchat and queue?
Michael Welsh
mwelsh@abwatley.com
Thu Jul 10 16:34:10 2003
I'm trying to learn how to use sockets in Python. =20
Using samples available on the web, I've managed to set up a simple echo=20
'server' using asyncore and asynchat (below). I built a small GUI (wxPytho=
n)=20
client that sends a bit of text to the server and recieve it back. I can=20
even run multiple clients. The server responds to the client that sent the=
=20
message. Now, I'd like to take the next step and have the server respond =
to=20
ALL clients, regardless of which client sent the message.
=46rom my web browsing and book reading it may be suitable to use Queues. =
This=20
is where I am having difficulty. I'm probably way off, but.. I believe I=20
want the server to receive the clients' msgs and throw them into a queue. =
A=20
separate action would read from the queue and act on it (possibly sending i=
t=20
back out to all the clients then logging to a db).=20
I may not be on the right track, I can't find simple examples anywhere of=20
using queues with asyncore/asynchat.
Anybody have any insight?
Michael
p.s. I'm aware that twisted exits. I'm doing this exercise to get a bette=
r=20
understanding of the Python fundamentals.
p.p.s Python 2.2 on NT and Linux
# Simple Server --------------------------------------------------------
import asyncore
import asynchat
import socket
class MainServerSocket(asyncore.dispatcher):
def __init__(self, port):
print 'initing Listening Port'
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(('',port))
self.listen(5)
def handle_accept(self):
newSocket, address =3D self.accept()
print "Connected from", address
SecondaryServerSocket(newSocket)
class SecondaryServerSocket(asynchat.async_chat):
def __init__(self, *args):
print 'initing OutBound Port'
asynchat.async_chat.__init__(self, *args)
self.set_terminator('\n')
self.data =3D []
def collect_incoming_data(self, data):
self.data.append(data)
def found_terminator(self):
self.push(''.join(self.data))
self.data =3D []
def handle_close(self):
print "Disconnected from", self.getpeername()
self.close()
MainServerSocket(50006)
asyncore.loop()
# -------------------------------------------------------------