考虑实现一个服务器, 在8007端口提供服务, 客户端连接上后, 发送一段文字, 然后断开.
代码:
- # -*- coding: utf-8 -*-
- from twisted.internet.protocol import Protocol, Factory
- from twisted.internet import reactor
- class QOTD(Protocol):
- def connectionMade(self):
- self.transport.write("An apple a day keeps the doctor away/r/n")
- self.transport.loseConnection()
- #开始启动服务
- factory = Factory()
- factory.protocol = QOTD
- #监听8007端口
- reactor.listenTCP(8007, factory)
- reactor.run()
运行:
python server.py
连接:
FunCat:~ Daniel$ telnet 127.0.0.1 8007
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
An apple a day keeps the doctor away
Connection closed by foreign host.
本文介绍使用 Python 的 Twisted 框架实现一个简单的 TCP 服务器的过程。该服务器监听 8007 端口,当客户端连接并发送消息后,服务器返回固定的文字信息并断开连接。
481

被折叠的 条评论
为什么被折叠?



