- 创建 Twisted Reactor TCP 服务器
$ vim tsTservTW.py
1 #!/usr/bin/python3
2
3 from twisted.internet import protocol, reactor
4 from time import ctime
5
6 PORT = 6666
7
8 class TSServProtocol(protocol.Protocol):
9
10 def connectionMade(self):
11 """重写:当客户端连接时就会执行"""
12 # 获取连接的主机信息
13 clnt = self.clnt = self.transport.getPeer().host
14 print('[+] ...connected from: %s' % str(clnt))
15
16 def dataReceived(self, data):
17 """重写:当接受到客户端发送的数据是会执行"""
18 # 给客户端回信
19 self.transport.write(b'[%s] %s' % (bytes(ctime(), 'utf-8'), data))
20
21 # 实例化一个协议工厂
22 factory = protocol.Factory()
23 factory.protocol = TSServProtocol
24 print('waiting for connection...')
25 # 安装TCP监听器
26 reactor.listenTCP(PORT, factory)
27 reactor.run()
- 创建 Twisted Reactor TCP 客户端
$ vim tsTclntTW.py
1 #!/usr/bin/python3
2
3 from twisted.internet import protocol, reactor
4
5 HOST = '127.0.0.1'
6 PORT = 6666
7
8 class TSClntProtocol(protocol.Protocol):
9
10 def sendData(self):
11 data = input(">>> ")
12 if data:
13 print("[+] ...sending %s..." % data)
14 self.transport.write(bytes(data, 'utf-8'))
15 def connectionMade(self):
16 self.sendData()
17
18 def dataReceived(self, data):
19 print(data.decode('utf-8'))
20 self.sendData()
21
22
23 class TSClntFactory(protocol.ClientFactory):
24 protocol = TSClntProtocol
25 clientconnetionLost = clientConnectionFailed = lambda self, connector, reason: reactor.st op()
26
27 # 创建一个客户端工厂
28 reactor.connectTCP(HOST, PORT, TSClntFactory())
29 reactor.run()
- 执行 TCP 服务器和客户端
# 终端1
$ ./tsTservTW.py
waiting for connection...
[+] ...connected from: 127.0.0.1
# 终端2
$ ./tsTclntTW.py
>>> hello
[+] ...sending hello...
[Mon Nov 27 19:53:08 2017] hello
>>> good bey.
[+] ...sending good bey....
[Mon Nov 27 19:53:19 2017] good bey.
网友评论