Chapter 2. Building Basic Clients and Servers
The best way to learn about the components of a Twisted application is to dive right into some examples. This chapter will introduce you to the reactor event loop, transports, and protocols through implementations of a few basic TCP servers and clients.
A TCP Echo Server and Client
Skim the code for the TCP echo server and client pair in Examples 2-1 and 2-2. The server’s job is to listen for TCP connections on a particular port and echo back anything it receives. The client’s job is to connect to the server, send it a message, receive a response, and terminate the connection.
from
twisted.internet
import
protocol
,
reactor
class
Echo
(
protocol
.
Protocol
):
def
dataReceived
(
self
,
data
):
self
.
transport
.
write
(
data
)
class
EchoFactory
(
protocol
.
Factory
):
def
buildProtocol
(
self
,
addr
):
return
Echo
()
reactor
.
listenTCP
(
8000
,
EchoFactory
())
reactor
.
run
()
from
twisted.internet
import
reactor
,
protocol
class
EchoClient
(
protocol
.
Protocol
):
def
connectionMade
(
self
):
self
.
transport
.
write
(
"Hello, world!"
)
def
dataReceived
(
self
,
data
):
"Server said:"
,
data
self
.
transport
.
loseConnection
()
class
EchoFactory
(
protocol
.
ClientFactory
):
def
buildProtocol
(
self
,
addr
):
return
EchoClient
()
def
clientConnectionFailed
(
self
,
connector
,
reason
):
"Connection failed."
reactor
.
stop
()
def
clientConnectionLost
(
self
,
connector
,
reason
):
"Connection lost."
reactor
.
stop
()
reactor
.
connectTCP
(
"localhost"
,
8000
Get Twisted Network Programming Essentials, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.