There is a Twisted server which gives responses to clients' requests. The "LineOnlyReceiver" is used for the protocol design. The process should go as following:
A client sends a request to the server (such as "TEMP?" asking the temperature), then the number of request on the server should increase by 1. After the server sends back the response, the number should decrease by 1. However, during the request ("TEMP?") being processed by the server, there could be other clients sending requests to the server, the number of requests on the server should vary with time.
So how to keep track of the number of requests on the server on-the-fly? Currently, the "lineReceived" method is used to receive requests from clients and send back responses (other codes omitted):
Class SimProtocol(LineOnlyReceiver):
def lineReceived(self, request):
self.factory.taskNumber[request.strip()] += 1
print 'Task number: ', self.factory.taskNumber[request.strip()]
time.sleep(10)
resp = self.factory.getResponse(request.strip())
self.transport.write(resp)
self.factory.taskNumber[request.strip()] -= 1
print 'Task number: ', self.factory.taskNumber[request.strip()]
The 10 seconds delay is added in the middle on purpose to simulate the processing time of the requests. During the 10 seconds, there are several other requests being sent to the server, but the server didn't respond to other requests until it finishes the current one. In other words, the "print" statements always show the task number is 1, 0, 1, 0..., no matter how many clients are sending requests.
So what kind of design approach (probably a totally different one, like getting the reactor queue size could do?) should be used to accomplish this functionality (keep track of the number of requests on the server on-the-fly)?