[Twisted-Python] Simple bidirectional Socket Client
raketenschnitzel at gmx.de
Fri Jun 14 06:11:20 MDT 2013
i'm new to twisted, but i want to use it in a project for dealing with
the socket connection to a server for receiving and sending data.
I already did some projects in Delphi and there you have an build-in
eventdriven socket class. Python itself lacks at this feature (afaik)
and so i stumpled upon twisted. Since its only a small part of my task,
im looking for an easy solution but after consulting google for two days
and testing around im still failing at get it working.
What i got so far:
# send Greeting
self.factory.isConnected = True
def dataReceived(self, data):
"Parse received data and send corresponding Message."
def connectionLost(self, reason):
#try to reconnect
self.factory.isConnected = False
print "connection lost"
def sendMessage(self, data):
print 'Send:', data
protocol = ControllerProtocol
def __init__(self, Host, Port):
if isinstance(Host, str) and isinstance(Port, int) :
self.myHost = Host
self.myPort = Port
self.isConnected = False
print 'Going To connect'
reactor.connectTCP(self.myHost, self.myPort, self)
def buildProtocol(self, addr):
p = ClientFactory.buildProtocol(self, addr)
self.connectedProtocol = p
def sendMessage(self, Message):
def reactOnReceive(self, String):
#here i parse the received string for different requests after
converting it to json and update values of the operator
self.myCommunicator = Communicator("192.168.1.12", 815)
do other stuff ...
I want an Operator Object that builds the Communicator. The communicator
updates values of the Operator asynchronously if it receives messages.
Each 10 secs the Operator will initiate a Communicator.sendMessage to
send a status information to the server.
1) Is it possible to solve my task like this with twisted and if so, how
do I get my Communicator to not block my Operator?
2) If twisted is not the easiest way for this approach, do i have
alternatives? I want at least something event driven. I also read about
the asyncore packages, but people often recommend twisted over asyncore.
I simply want to send and receive message with a "threaded" communicator
class, while doing other stuff in my Operator.
Thanks a lot for your help,
More information about the Twisted-Python