我在试着理解Bayeux协议。我还没有找到一个网络资源来详细解释bayeux客户端在技术上将如何工作。
来自这资源,
Bayeux协议要求新客户端发送的第一条消息是握手消息(在/meta/握手通道上发送的消息)。 客户端处理握手应答,如果成功,则通过交换连接消息(在/meta/connect通道上发送的消息),在幕后启动与服务器的心跳机制。 这种心跳机制的细节取决于所使用的客户端传输,但可以看作是客户机发送了一条连接消息,并期望在一段时间后收到答复。 连接消息继续在客户端和服务器之间流动,直到任何一方通过发送断开消息(在/meta/disconnect通道上发送的消息)决定断开连接为止。
我用Java方法编写,首先进行握手,然后订阅特定的频道。我使用Apache库来执行HTTP请求。
现在是连接的一部分。
我的理解是,我需要保持一个请求对bayeux服务器开放,每当我收到响应时,再发出另一个请求。
下面的代码是我写的。我的理解正确吗?这个bayeux客户端是否显示了正确的连接功能?(请忽略缺少的断开、取消订阅方法)
此外,我已经在bayeux服务器上测试了代码,并且它工作正常。
/* clientId - Unique clientId returned by bayeux server during handshake
responseHandler - see interface below */
private static void connect(String clientId, ResponseHandler responseHandler)
throws ClientProtocolException, UnsupportedEncodingException, IOException {
String message = "[{\"channel\":\"/meta/connect\","
+ "\"clientId\":\"" + clientId + "\"}]";
CloseableHttpClient httpClient = HttpClients.createDefault();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (!doDisconnect) {
try {
CloseableHttpResponse response = HttpPostHelper.postToURL(ConfigurationMock.urlRealTime,
message, httpClient, ConfigurationMock.getAuthorizationHeader());
responseHandler.handleResponse(response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
/*Simple interface to define what happens with the response when it arrives*/
private interface ResponseHandler {
void handleResponse(CloseableHttpResponse httpResponse);
}
public static void main(String[] args) throws Exception{
String globalClientId = doHandShake(); //assume this method exists
subscribe(globalClientId,"/measurements/10500"); //assume this method exists
connect(globalClientId, new ResponseHandler() {
@Override
public void handleResponse(CloseableHttpResponse httpResponse) {
try {
System.out.println(HttpPostHelper.toStringResponse(httpResponse));
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}发布于 2016-02-12 13:59:48
你的代码不正确。
/meta/connect通道上的消息没有subscription字段。
订阅必须在/meta/subscribe频道上发送。
为了获得更多的细节,您需要学习Bayeux规范,特别是元信息部分和事件消息部分。
一个建议是使用启动CometD演示并查看客户端交换的消息,并在您的实现中模仿这些消息。
https://stackoverflow.com/questions/35361231
复制相似问题