连接 stomp 客户端后添加主题/订阅
Posted
技术标签:
【中文标题】连接 stomp 客户端后添加主题/订阅【英文标题】:Add topic/subscription after stomp client is connected 【发布时间】:2017-01-31 08:41:41 【问题描述】:我目前正在使用 https://github.com/NaikSoftware/StompProtocolandroid 使用 STOMP 连接 websocket。我有一个简单的实现
public class TestActivity extends AppCompatActivity
private StompClient mStompCLient;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
mStompCLient = Stomp.over(WebSocket.class, BASE_URL);
mStompCLient.topic("/topic/online/" + mSharedPreferences.getPrivateKey()).subscribe(new Subscriber<StompMessage>()
@Override
public void onCompleted()
Log.i(TAG, "/topic/online/ onCompleted: ");
@Override
public void onError(Throwable e)
Log.i(TAG, "/topic/online/ onError: " + e.getMessage());
@Override
public void onNext(StompMessage stompMessage)
Log.d(TAG, "/topic/online/ onNext: " + stompMessage.getPayload());
String content = "";
JSONObject jsonResponse = null;
try
jsonResponse = new JSONObject(stompMessage.getPayload());
content = jsonResponse.getString("uri");
catch (JSONException e)
e.printStackTrace();
listenToUpdatesFromFinalUri(content);
);
mStompCLient.lifecycle().subscribe(lifecycleEvent ->
Log.i(TAG, "onCreate: " + lifecycleEvent.getMessage());
switch (lifecycleEvent.getType())
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed : " + lifecycleEvent.toString() + " :msg: " + lifecycleEvent.getMessage() + " :escep: " + lifecycleEvent.getException() + " :headers: " + lifecycleEvent.getHandshakeResponseHeaders() + " :type: " + lifecycleEvent.getType());
break;
);
mStompCLient.connect();
private void listenToUpdatesFromFinalUri(String content)
mStompCLient.topic(content).subscribe(new Subscriber<StompMessage>()
@Override
public void onCompleted()
Log.i(TAG," onCompleted: ");
@Override
public void onError(Throwable e)
Log.i(TAG, " onError: " + e.getMessage());
@Override
public void onNext(StompMessage stompMessage)
Log.d(TAG, " onNext: " + stompMessage.getPayload());
);
@Override
protected void onStop()
super.onStop();
disconnectStomp();
private void disconnectStomp()
mStompCLient.disconnect();
这里我尝试监听建立连接后服务器发送的新订阅频道。如果在调用 connect 之前调用 subscribe() ,它就会起作用。但是在listenToUpdatesFromFinalUri() 函数中订阅的最终uri/订阅频道不是静态的,所以我需要在连接之前不能添加订阅。我目前无法获得最终 uri/订阅的回复。任何帮助表示赞赏。
【问题讨论】:
【参考方案1】:新版本1.1.6已解决该问题
【讨论】:
以上是关于连接 stomp 客户端后添加主题/订阅的主要内容,如果未能解决你的问题,请参考以下文章
分布式WebSocket - 5SprintBoot集成STOMP协议,session权限管理