Write a TCP client with Python Twisted

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.

Thing you want to do

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.

I will write

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)

Try to run

Connect to the TCP server using the reactor module.

from twisted.internet import reactor

reactor.connectTCP('127.0.0.1', 5403, SomeServerClient())
reactor.run()

Other

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.

I want to read it together

Recommended Posts

Write a TCP client with Python Twisted
Write a batch script with Python3.5 ~
"First Elasticsearch" starting with a python client
I want to write to a file with Python
Make a fortune with Python
[Python] A memo to write CSV vertically with Pandas
Write to csv with Python
A program to write Lattice Hinge with Rhinoceros with Python
Create a directory with python
Let's make a websocket client with Python. (Access token authentication)
[Python] What is a with statement?
Write a binary search in Python
How to write a Python class
Solve ABC163 A ~ C with Python
A python graphing manual with Matplotlib.
[Python] Write to csv file with Python
Let's make a GUI with python.
Create a virtual environment with Python!
Write A * (A-star) algorithm in Python
I made a fortune with Python.
Write a Residual Network with TFLearn
Building a virtual environment with Python 3
Solve ABC168 A ~ C with Python
Make a recommender system with python
Write a pie chart in Python
[Python] Generate a password with Slackbot
Solve ABC162 A ~ C with Python
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
Let's make a graph with python! !!
Write a super simple TCP server
[Python] Inherit a class with class variables
I made a daemon with Python
Write a stacked histogram with matplotlib
[Pyenv] Building a python environment with ubuntu 16.04
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Create a Python function decorator with Class
Creating a simple PowerPoint file with Python
Building a Python3 environment with Amazon Linux2
A simple HTTP client implemented in Python
Install Python as a Framework with pyenv
Build a blockchain with Python ① Create a class
Simple Slack API client made with Python
Add a Python data source with Redash
Create a dummy image with Python + PIL.
Write the test in a python docstring
I made a character counter with Python
[Python] Drawing a swirl pattern with turtle
Periodically perform arbitrary processing with Python Twisted
I drew a heatmap with seaborn [Python]
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
A memo with Python2.7 and Python3 on CentOS
Building a Python 3.6 environment with Windows + PowerShell
Map rent information on a map with python
Search the maze with the python A * algorithm
Write a short property definition in Python
Daemonize a Python web app with Supervisor
Let's make a voice slowly with Python
Created a darts trip with python (news)
Write a Caesar cipher program in Python