代码之家  ›  专栏  ›  技术社区  ›  al_mukthar

从Android向Spring Boot websocket端点方法发送消息

  •  1
  • al_mukthar  · 技术社区  · 7 年前

    这是我在spring boot中的套接字配置:

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig extends 
    AbstractWebSocketMessageBrokerConfigurer {
    
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
    
    @Override
    public void registerStompEndpoints(StompEndpointRegistry 
    stompEndpointRegistry) {
    
    stompEndpointRegistry.addEndpoint("/message").setAllowedOrigins("*");
    }
    }
    

    这是我的信息控制器

    @Controller
    public class MessageController {
    
    private static final Logger logger = 
    LoggerFactory.getLogger(MessageController.class);
    
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting sendResponse(Message incomingMessage) {
        logger.debug(incomingMessage.getMessage());
        return new Greeting("Hello " + incomingMessage.getMessage());
    }
    }
    

    我使用android中的okhttp,使用以下代码连接到套接字:

    public class MainActivity extends AppCompatActivity {
    
    private ActivityMainBinding mBinding;
    private static String TAG;
    public static final String SOCKET_ADDR = 
    "wss://androidspy.herokuapp.com/message";
    private OkHttpClient mOkHttpClient;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = DataBindingUtil.setContentView(this, 
    R.layout.activity_main);
    
    TAG = this.getClass().getSimpleName();
    initObjects();
    initListeners();
    initiateHandshake();
    }
    
    private void initObjects() {
    mOkHttpClient = new OkHttpClient();
    }
    
    private void initListeners() {
    //mBinding.btnConnect.setOnClickListener(this::initiateHandshake);
    }
    
    private void initiateHandshake() {
    Request socketRequest = new Request.Builder()
        .url(SOCKET_ADDR)
        .build();
    
    WebSocket webSocket = mOkHttpClient.newWebSocket(socketRequest, new 
    WebSocketListener() {
      @Override
      public void onOpen(WebSocket webSocket, Response response) {
        webSocket.send("Hi Server");
        Log.d(TAG, String.format("Connected to 
    %s",webSocket.request().url()));
      }
    
      @Override
      public void onMessage(WebSocket webSocket, String result) {
        Log.d(TAG, String.format("Received %s" ,result));
      }
     });
    mOkHttpClient.dispatcher().executorService().shutdown();
    }
    

    sendResponse() @MessageMapping("/hello)

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ali Yusuf    7 年前

    尽量不要关闭连接 mOkHttpClient.dispatcher().executorService().shutdown();