I am trying to write a server using Twisted framework and would like to receive the data multiple times
class Echo(Protocol):
def connectionMade(self):
print " got connection from : " + str(self.transport.getPeer())
def dataReceived(self, data):
'''
get the client ip
'''
if(len(data)>40):
'''
initial setup message from the client
'''
client_details = str(self.transport.getPeer())#stores the client IP as a string
i = client_details.find('\'')#process the string to find the ip
client_details = client_details[i+1:]
j = client_details.find('\'')
client_ip = client_details[:j]
'''
Extract the port information from the obtained text
'''
data = data.split('@')
port1 = data[0]
port2 = data[1]
port3 = data[2]
if int(data) == 1:
method1(client_ip,port1)
if int(data) == 2:
method2(client_ip,port2)
My question: The method1 and method2 are called only if it receives a message from the client with appropriate integer data in it. Is there a way in which I can wait on client for receiving the data inside the dataReceived() method or should I just do it sequentially in the dataReceived() method itself?
The dataReceived method is invoked when some data is received. In order to wait for more data to be received, you just have to return from dataReceived so that it can be called again.
Also, TCP is not message-based, it is stream-based. Your dataReceived method cannot count upon always receiving a complete message, so your example code is incorrect. See this frequently asked question on the Twisted Matrix Labs website for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With