简体   繁体   English

通过持久连接实现与POST(HTTP)的推送技术连接

[英]Implementing push technology connection with POST (HTTP) through persistent connection

I am developing a text message type app. 我正在开发短信类型的应用程序。

The messages are communicated only in direction ((1)Server -> (n)Client) 消息仅在((1)Server->(n)Client)方向上传递

  • Server: PHP (LAMP) 伺服器:PHP(LAMP)
  • Clients: Android (Java) 客户端:Android(Java)

One option is to ask to server every x seconds "new messages?". 一种选择是每隔x秒向服务器请求“新消息?”。 This option is not worth me because creating a HTTP connection every x seconds for each device is very expensive. 这个选项不值得我这样做,因为每x秒为每个设备创建一个HTTP连接非常昂贵。 For example 10 000 devices creating new connection every 5 seg. 例如,每5个段产生10,000个设备创建新连接。 This option is like the system is working now. 此选项就像系统现在正在运行。

Option two is that I want to implement, but I don't know how do it in (Java-PHP). 选项二是我想实现,但是我不知道如何在(Java-PHP)中实现。

The idea is the following, based on push technology: 基于推送技术的想法如下:

Maintain a connection from the client to the server open continuously. 保持从客户端到服务器的连接不断打开。 That connection will never transport any data. 该连接将永远不会传输任何数据。

When the server wants to send a message to a client, force close of continuous connection. 当服务器要向客户端发送消息时,强制关闭连续连接。

Then the client instantly receives the event that the connection has been closed. 然后,客户端立即收到连接已关闭的事件。 In this case the event of closed connection means "new messages", so the client will open POST connection to get data. 在这种情况下,关闭连接的事件意味着“新消息”,因此客户端将打开POST连接以获取数据。

How can maintain an open connection between Java and PHP continuously and that the server has the ability to close it instantly? 如何才能持续保持Java和PHP之间的开放连接以及服务器是否能够立即关闭它?

This is working code for POST connection between java and PHP, to try if from this code is possible open connection indefinitely. 这是用于Java和PHP之间的POST连接的工作代码,以尝试从此代码中无限期地打开连接。

Php: PHP的:

<?php    
    if (isset($_POST['myId']))
    {       $in = $_POST['myId'];               
            //(...)             
            echo $myResponse;               
    }        
?>

Java: Java的:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);                      

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair(key,content));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

WebSocket should be the best solution in your case. WebSocket应该是您的最佳解决方案。 You can find many libraries for different languages even for PHP and Java. 您可以找到许多针对不同语言的库,甚至适用于PHP和Java。 WebSocket allows you to create persistent bi-directional connection. WebSocket允许您创建持久的双向连接。 So you can push a message from a server to the client without any client-side request. 因此,您可以将消息从服​​务器推送到客户端,而无需任何客户端请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM