简体   繁体   中英

Python Twisted: read from file and send as TCP server

I am completely new to Twisted, but it looks very promising for my project.

I would like to write a Python Twisted application which reads a record from text file every x seconds and contemporary listen on a TCP port (acting as TCP server). If no clients are connected to the TCP server the records are just discarded. If one or more clients are connected to the TCP server, the records are sent to all clients (all clients will receive the same line of the text file)

Can Twisted make this possible with a reasonable amount of LOCs?

Could anybody suggest an example to start with?

Thanks C

Twisted's documentation includes information about how to run a TCP server . It also includes an information about how to perform work based on the passage of time . This should cover most of what you need to know.

Jean-Paul,

thanks for your answer. Below is what i put together. The program is sending strings with time stamps to one or more clients connected to the server. Read synchronously from file in this scenario is very simple so i just use a fixed string with the time stamp.

My next step is to substitute the datetime.datetime.now() function call with a call to web service. Basically what i would like to create is kind of proxy that is

  • client versus a web service and invoke it every x seconds to get the data

  • TCP server versus a set of clients to stream data continuously, or better to say once a new data chunk is available (as is doing the example below)

The questions are:

Can you point me to an example of a similar system?

How can I combine the runEverySecond() method call with an asynchronous call to the web service using TCPClient capability of Twisted?

Thanks

C

from twisted.internet import protocol, reactor
from twisted.internet import task
import datetime

class Stream(protocol.Protocol):
    def __init__(self, f):
        self.factory = f

    def connectionMade(self):
        self.start = True

    def forward(self, data):
        if self.start:
            self.transport.write(data)


class StreamFactory(protocol.Factory):
    def __init__(self):
        self.connections = []

    def buildProtocol(self, addr):
        s = Stream(self)
        self.connections.append( s )
        return s

    def runEverySecond(self):
        for c in self.connections:
            c.forward( str(datetime.datetime.now()) )


f = StreamFactory()
l = task.LoopingCall(f.runEverySecond)
l.start(1.0) # call every second
reactor.listenTCP(8000, f)
reactor.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM