user3051473 user3051473 - 6 months ago 35
Python Question

How To Use Http Push With Python Server And Android Client?

I have a simply Http Server written by Python's BaseHTTPRequestHandler.
With a client written by Java in Android with HttpClient.
And I want to push data from python server to client java:
So I try to make a while True loop at server, A few piece of server's code:

def do_POST(self):
# receive POST data from client
# ...
# Then I want to keep alive this connection
self.send_response(200)
while True:
self.send_response(200)
time.sleep(5)

And HttpClient and MultipartEntity for java Client:
protected String doInBackground() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.104:8089");

MultipartEntity entity = new MultipartEntity();

entity.addPart("type", new StringBody("audio"));
byte []dataByte = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
entity.addPart("data", new ByteArrayBody(dataByte, "data"));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);

// Please see This log will never print because blocked above
Log.d("MainActivity", "Server response");
}


I want to receive server's response contiguously after httpClient.execute().
But I am blocked at the last source of client because the While True loop at server.

I guess httpClient.execute() is waiting for the http socket closing?
Can you please help me for how to handle this situation?
I have searched the push technology and seems long pulling is another way to push.

But I think push is more better solution for my situation.

Answer

I think that the problem is in the server side code, where:

while True:
    self.send_response(200)
    time.sleep(5)

The do_Post method is an handler, and the self.send_response(200) just set the HTTP status; but it doesn't actually send something over the wire. And you hang in there forever.

I think that you should review completely the architecture of your app, server side and client side(I maybe wrong, but DefaultHttpClient isn't deprecated [1] ?

Have you considered using websockets : https://github.com/koush/android-websockets ?

[1] http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DefaultHttpClient.html