Twisted

Twisted is an event-driven networking engine written in Python and licensed under the open source MIT license.

Install from source

Test installation

Slackbuild

Slackware64 14: python-twisted-13.2.0-x86_64-1_SBo.tgz

Echo server

   1 from twisted.internet import protocol, reactor
   2 
   3 class Echo(protocol.Protocol):
   4     def dataReceived(self, data):
   5         self.transport.write(data)
   6 
   7     def connectionMade(self):
   8         print('Connection made')
   9 
  10     def connectionLost(self,reason):
  11         print('Connection lost')
  12 class EchoFactory(protocol.Factory):
  13     def buildProtocol(self, addr):
  14         return Echo()
  15 
  16 if __name__=='__main__':
  17     reactor.listenTCP(1234, EchoFactory())
  18     reactor.run()

Echo client

   1 import threading
   2 import time
   3 import socket
   4 
   5 class Client (threading.Thread):
   6     def __init__(self):
   7         threading.Thread.__init__(self) #required
   8                 
   9     def run(self):
  10         for x in range(1,100):
  11             HOST = 'localhost'
  12             PORT = 1234
  13             s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14             print('connecting...')
  15             s.connect((HOST, PORT))
  16             print('sending config...')
  17             s.send('test')
  18             s.close()
  19             print('complete')
  20 
  21 if __name__=='__main__':
  22 
  23     clients=[]
  24     for x in range(1,100):
  25         clients.append( Client() )
  26 
  27     for c in clients:
  28         c.start()

Python/Twisted (last edited 2015-03-12 21:33:37 by 54)