Twisted TCP Server Example

Within a few minutes of reading the Twisted how-to tutorials for getting started with creating a simple TCP server" I had the response page serving correctly on my local machine.

Twisted installed on my Mac running Mac OS X 10.5.2 Leopard without a single warning. This is notable only because A.) I'm a moron, normally needing to use the gcc equivalent of a crowbar to wedge software into my development system, and B.) Once again I find that Leopard's pre-installed open-source software meets the minimal requirements for additional software so I can avoid dependence hell once again. FANTASTIC!

Below I have the Python script posted for the TCP server which follows the Twisted example for the most part. This service will respond with a predefined HTML statement to a request made to port 8007. The response doesn't need to be as drab (stable) as HTML. The self.transport.write can be altered to what is needed for your application.

Everything a language/computer/technology should do is _work_ and _get out of the way_ so that the task it is created or used for can be accomplished without out too much of that muck. Since everything is just a more complex version of simple pieces, like binary code or even DNA, incredible possibilities are possible once the simple piece can be created.

This is why I like Twisted. It was simple to implement and in some respects has gotten out of the way and allowed my mind to begin wondering past the "first response" and on to further tasks such as "what this should do".


#!/usr/bin/python

greeting = """
HELLO WORLD!
This is a TCP/IP Server written in Python using 
the Twisted networking framework.

It will respond on port 8007 of the local host
With a predefined greeting.
"""
print greeting

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class QOTD(Protocol):
	def connectionMade(self):
		self.transport.write("""
<!DOCTYPE html PUBLIC>
<html>
	<head>
		<title>Twisted TCP Server Example</title>
	</head>
	<body>
		<h1>HELLO WORLD!</h1>
		<pre>
This is a TCP/IP Server written in Python using 
the Twisted networking framework.

Further instruction can be found here:
<a href="http://twistedmatrix.com/projects/core/documentation/howto/servers.html">
	Twisted Documentation: Writing Servers
</a>

This server will respond on port 8007 of the local host
With a predefined greeting.
		</pre>
	</body>
</html>""")
		self.transport.loseConnection()

# Then lines are Twisted magic:
factory = Factory()
factory.protocol = QOTD

# Running under :8007
# Should be > :1024
reactor.listenTCP(8007, factory)
reactor.run()

Take away

Twisted is an amazing, simple to use, light weight Python based networking framework. Anyone interested in building applications that require networking connectivity should take a look at this project.

About RSS Feed Search