I had to write a TCP client, so I searched. At first I wrote using the socket module, but using Twisted is simple. It was easy to write and retry, so somehow.
There is hardware that can periodically acquire sensor data and send it to the outside via TCP. It connects to this, logs the received data, and performs arbitrary processing.
The hardware that becomes the server is not a protocol that requires authentication or calling, it just spills data.
protocol.py
import logging
from twisted.internet.protocol import Protocol
logger = logging.getLogger(__name___)
#Class that handles the protocol
class SomeProtocol(Protocol):
def dataReceived(self, data):
logger.debug(u'data received. data: %s' % data)
#Write to log file
f = open('log.dat', 'ab')
f.write(data)
f.close()
client.py
import logging
from twisted.internet.protocol import ReconnectingClientFactory
from .protocol import SomeProtocol
logger = logging.getLogger(__name___)
#Client class. It is this class that actually performs the connection process.
class SomeServerClient(ReconnectingClientFactory):
protocol = SomeProtocol
def buildProtocol(self, addr):
"""Protocol class instantiation method
"""
logging.info(u'Successfully connected to %s' % addr)
self.resetDelay() #Restore the retry delay
protocol = self.protocol()
protocol.factory = self
return protocol
def startedConnecting(self, connector):
"""Called after connection
"""
logger.info(u'Started to connect.')
def clientConnectionLost(self, connector, reason):
"""Handler in case of loss of connection
"""
logger.warning(u'Lost connection. Reason: %s', reason)
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
def clientConnectionFailed(self, connector, reason):
"""Handler when connection fails
"""
logger.error(u'Connection failed. Reason: %s' % reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
Connect to the TCP server using the reactor module.
from twisted.internet import reactor
reactor.connectTCP('127.0.0.1', 5403, SomeServerClient())
reactor.run()
Twisted It's not very fast and gevent is good, so @masahif told me so I'll check it later.
This time, a single server and a single client only process the data that flows every second, so you don't have to worry about speed, and you can easily write what you want to do (retry processing), so Twisted It looks okay.
Recommended Posts