简体   繁体   English

如何在 android 上通过 spring 启动从 stomp websocket 接收消息?

[英]How to receive the message from stomp websocket with spring boot on android?

I've got the simple WebSocket example from https://spring.io/guides/gs/messaging-stomp-websocket/我从https://spring.io/guides/gs/messaging-stomp-websocket/得到了简单的 WebSocket 示例

package com.example.chatservice.message;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }
}
@Controller
public class ChatController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        return new Greeting("Hello from chat!");
    }
}

and I'd like to receive the Greeting message from the spring server to an android app.我想从 spring 服务器接收到 android 应用程序的Greeting消息。 I use https://github.com/NaikSoftware/StompProtocolAndroid as a stomp client我使用https://github.com/NaikSoftware/StompProtocolAndroid作为 stomp 客户端

package com.example.chatapp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import org.java_websocket.WebSocket;

import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.client.StompClient;

public class MainActivity extends AppCompatActivity {
    private StompClient mStompClient;
    public static  final String TAG="StompClient";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button view = (Button) findViewById(R.id.send_message);
        view.setOnClickListener(e->  new StompTask().execute(""));
    }

    private static class StompTask extends AsyncTask<String, Void, String> {
        private StompClient mStompClient;
        String TAG="LongOperation";

        @Override
        protected String doInBackground(String... params) {
            mStompClient = Stomp.over(WebSocket.class, "http://10.0.2.2:8080/gs-guide-websocket/websocket");
            mStompClient.connect();

            mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
                Log.d(TAG, topicMessage.getPayload());
            });

            mStompClient.lifecycle().subscribe(lifecycleEvent -> {
                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");
                        break;
                }
            });

            return "Executed";
        }
    }
}

and the connection to the和连接到

http://10.0.2.2:8080/gs-guide-websocket/websocket

works, because the log shows it's connected有效,因为日志显示它已连接

2022-01-18 14:04:56.486 23717-23752/com.example.chatapp D/LongOperation: Stomp connection opened

but it does not subscribe to the topic:但它不订阅主题:

mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
    Log.d(TAG, topicMessage.getPayload());
});

because when I set the breakpoint it doesn't ever hit it.因为当我设置断点时,它永远不会命中它。

how can I receive this message?我怎样才能收到这条消息?

I think everything looks awesome except "http://10.0.2.2:8080/gs-guide-websocket/websocket" should probably be "ws://10.0.2.2:8080/gs-guide-websocket/websocket" for the websocket.我认为一切看起来都很棒,除了 websocket 的"http://10.0.2.2:8080/gs-guide-websocket/websocket"应该是"ws://10.0.2.2:8080/gs-guide-websocket/websocket" .

The author of the librabry put this in their example code :图书馆的作者把这个放在他们的示例代码中:

`mStompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, "ws://" + ANDROID_EMULATOR_LOCALHOST + ":" + RestClient.SERVER_PORT + "/example-endpoint/websocket");` 

First of all I suppose you understand that if you don't send the proper message to the specified request topic, then you won't get anything here -首先,我想您明白,如果您没有向指定的请求主题发送正确的消息,那么您将不会在这里得到任何东西 -

mStompClient.topic("/topic/greetings").subscribe(topicMessage -> {
    Log.d(TAG, topicMessage.getPayload());
});

Today I had the issue where when sending a message,今天我在发送消息时遇到了问题,

mStompClient.send(REQUEST_TOPIC, requestAsString)

I also did not receive anything in the subscription.我也没有收到订阅中的任何内容。 The problem is that in addition to subscribing to the topic of receiving messages, you must subscribe to the topic of sending messages -问题是除了订阅接收消息的主题,还必须订阅发送消息的主题——

mStompClient.send(REQUEST_TOPIC, requestAsString)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                {
                                //onComplete
                                }, { error ->
                                  error.safeLog()
                                })

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

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