-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtwistedtest.py
More file actions
60 lines (44 loc) · 1.69 KB
/
twistedtest.py
File metadata and controls
60 lines (44 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# This tests the twisted module
from twisted.internet import reactor, protocol
# Server #
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"As soon as any data is received, write it back."
print('[Server] Received: "' + str(data) + '" from ' + str(self.transport.getPeer()))
self.transport.write(data)
def setupServer():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000,factory)
# Client #
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
print('[Client] Starting! My Ip-address: ' + str(self.transport.getHost()))
print('[Client] Sending message to server...')
self.transport.write("hello, world!")
def dataReceived(self, data):
"As soon as any data is received, write it back."
print('[Client] Server said: "' + str(data) + '"')
print('[Client] Terminating connection...')
self.transport.loseConnection()
def connectionLost(self, reason):
print('[Client] Connection closed.')
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print('[Client] Connection failed!')
reactor.stop()
def clientConnectionLost(self, connector, reason):
print('[Client] Connection lost.')
reactor.stop()
def setupClient():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
# Main #
def run():
setupServer()
setupClient()
reactor.run()