[nycbug-talk] twisted python resources
Bob Ippolito
bob
Sat Jan 29 12:24:08 EST 2005
On Jan 28, 2005, at 19:27, Pete Wright wrote:
> so i'm looking to write a "simple" messaging client
> for my network in python. it's more of an exercise to
> get me up to speed on programming in python, but will
> hopefully be usefull for us. as i know there are several
> python devs here...what would you all suggest as good
> places to look for examples, doc and tutorials.
>
> i've started checking out using twisted (as it seems
> quite popular and well designed)...so maybe something
> relating to doing dev with twisted would be helpfull
This is just an example of how much Twisted can do for you. This is a
trivial chat server for Macromedia Flash's XMLSocket feature.
Basically what it does is it forwards messages that a client sends to
every connected user (including the sender). It's great for testing.
For scalability and security purposes, you will of course want to use a
SSL connection and NOT forward every message to every user, but this is
good enough to get started with. The server has "no protocol", in that
it doesn't understand what's going on beyond using '\x00' (the C string
terminator, ASCII NULL, zero, whatever you want to call it) as a
delimiter. In this scenario, it is up to the clients to be "smart"
enough to figure out what to do. If you leave the delimiter
specification out, it will default to '\r\n' or '\n' (I don't recall)..
in which case you can telnet into it and it will redirect lines to all
connected clients.
-bob
# testserver.py
# run with twistd -noy testserver.py
# opens a TCP server on all interfaces on port 50000
from twisted.application import service, internet
from twisted.protocols import basic
from twisted.internet import protocol
class MyChat(basic.LineOnlyReceiver):
delimiter = '\x00'
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.sendLine(message)
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("TrivialServer")
internet.TCPServer(
50000, factory,
).setServiceParent(application)
More information about the talk
mailing list