用Python编写日间客户端最简单的方法是什么?
如果有更多未知大小但仍然是纯文本的数据 - 在服务器关闭连接之前我该如何阅读?
答案 0 :(得分:3)
这有效:
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "time.nist.gov"
port = 13
s.connect((host,port))
while True:
data = s.recv(10000)
if data:
print data
else:
break
s.close()
答案 1 :(得分:1)
#!/usr/bin/env python
import socket
from contextlib import closing as C
address = "time.nist.gov", socket.getservbyname('daytime')
with C(socket.create_connection(address, timeout=2)) as conn:
with C(conn.makefile()) as f:
print f.read(),
解决方案:
白天应该只有一行。
这是twisted
版本:
#!/usr/bin/env python
import sys
from twisted.internet import protocol, reactor
class EchoClientFactory(protocol.ClientFactory):
protocol = lambda _: protocol.ConsumerToProtocolAdapter(sys.stdout)
def clientConnectionLost(self, connector, reason):
reactor.stop()
def clientConnectionFailed(self, connector, reason):
print reason.value
reactor.stop()
host, port = "time.nist.gov", 13
reactor.connectTCP(host, port, EchoClientFactory(), timeout=2)
reactor.run()
答案 2 :(得分:0)
使用Twisted - 获取概念需要一些时间,但它会摇滚!
从教程http://twistedmatrix.com/documents/current/core/howto/index.html开始 - 前两个就足够了。