首页 > 解决方案 > 你如何从 Java 中的 websocket 流中读取/接收消息?

问题描述

所以我刚开始尝试使用 Websockets。我要做的就是从这个 Websocket 流中读取消息。我创建了一个简单的 Spring 应用程序只是为了开始,但我无法从流中接收/读取任何消息。握手成功(我可以从日志中收集到)。这就是它的样子——请原谅那些糟糕的代码,我会在我的基础上工作的那个。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.OnMessage;
import java.net.URI;
import java.util.concurrent.ExecutionException;

@SpringBootApplication
public class DemoApplication extends TextWebSocketHandler {

    private WebSocketSession clientSession;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received msg: "+message);
    }
    public DemoApplication () throws ExecutionException, InterruptedException {
        StandardWebSocketClient webSocketClient = new StandardWebSocketClient();
        this.clientSession = webSocketClient.doHandshake(this, new WebSocketHttpHeaders(),
                URI.create("wss://hostname.com/")).get(); 

        System.out.println("HANDSHAKE DONE!!!");
    }

}

从到目前为止我在教程中阅读的内容来看,@OnMessage当应用程序接收到消息时会触发,对吗?但我@OnMessage的从未被触发。我在这里从根本上错过了什么吗?我真的,真的很陌生!

标签: javaspringspring-bootwebsocket

解决方案


推荐阅读