如何在Python服务器和Android客户端上使用httppush?

2024-09-30 16:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由Python的BaseHTTPRequestHandler编写的简单的Http服务器。 在Android中用Java编写的HttpClient。 我想把数据从python服务器推送到客户端java: 所以我试着在服务器上做一个while-True循环,服务器的一些代码:

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");
    }

我想在以后连续接收服务器的响应httpClient.execute(). 但是我在客户端的最后一个源被阻塞了,因为服务器上的While True循环。在

我想是吧httpClient.execute()正在等待http套接字关闭? 你能帮我解决这个问题吗? 我已经搜索了推送技术,似乎长拉是另一种推送方式。在

但我认为推送更适合我的情况。在


Tags: self服务器true客户端newexecutedataresponse
1条回答
网友
1楼 · 发布于 2024-09-30 16:30:01

我认为问题出在服务器端代码中,其中:

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

do_Post方法是一个处理程序,并且self.send_响应(200)只需设置HTTP状态;但实际上它并不通过网络发送内容。你会永远坚持下去。在

我认为你应该彻底回顾一下你的应用程序的架构,服务器端和客户端(我可能错了,但是DefaultHttpClient不是不推荐使用的[1]?在

您是否考虑过使用websockets:https://github.com/koush/android-websockets?在

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

相关问题 更多 >