java - 你如何从 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
的从未被触发。我在这里从根本上错过了什么吗?我真的,真的很陌生!
解决方案
推荐阅读
- c# - 使用参数在 SQL 中的同一列上搜索多个部分匹配项
- rust - How do I write to a file from different threads in Rust?
- tizen - Tizen 4:为什么一个盒子容器不能容纳另一个布局?
- msbuild - 如何在 MSBuild 中获取目标操作系统
- python - 如何比较2列值并获取python中匹配对的计数
- .net - 如何在winforms中为动态创建的TexBox设置值
- python - 如何在 django 中从预定义的列表/字典而不是数据库 id 呈现视图?
- uitextview - 如何从 Swift 中的 UITextView 获取链接范围
- c++ - 为什么关联容器中的 end() 元素打印的值与最后一个元素相同?
- ignite - Apache Ignite.NET:一些 Ignite 节点在更新到 v2.9 后无法启动 - 检测到堆栈粉碎