开发者

Easiest "daytime" service client in Python?

What's the easiest way to write a daytime client in Python?

And if there's more data of unknown size but still plain text - how do I read until 开发者_JAVA技巧the server closes the connection?


This works:

#!/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()


#!/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(),

The solution:

  • cleanly finalizes resources
  • may eat your memory if the service misbehaves; though rfc 867 says:

    The daytime should be just one line.

Here's a twisted version:

#!/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()


Use Twisted - it will take some time to get the concept, but it rocks!

Start with tutorials http://twistedmatrix.com/documents/current/core/howto/index.html - first two should be enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜