我使用Vert.x 3实现websockets。
场景很简单:从客户端打开套接字做一些阻塞'在顶点垂直工作器上工作,当完成响应时,客户端的答案(通过打开的套接字)
如果我做得对,请告诉我:
创建了VertxWebsocketServerVerticle。一旦websocket打开并请求来自客户端,我就使用eventBus并将消息传递给
EventBusReceiverVerticle。我正在做阻止操作。
我实际上是如何将响应发送回VertxWebsocketServerVerticle并将其发送回客户端?
代码:
主要课程:
public static void main(String[] args) throws InterruptedException {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new EventBusReceiverVerticle("R1"),new DeploymentOptions().setWorker(true));
vertx.deployVerticle(new VertxWebsocketServerVerticle());
}
VertxWebsocketServerVerticle:
public class VertxWebsocketServerVerticle extends AbstractVerticle {
public void start() {
vertx.createHttpServer().websocketHandler(webSocketHandler -> {
System.out.println("Connected!");
Buffer buff = Buffer.buffer().appendInt(12).appendString("foo");
webSocketHandler.writeFinalBinaryFrame(buff);
webSocketHandler.handler(buffer -> {
String inputString = buffer.getString(0, buffer.length());
System.out.println("inputString=" + inputString);
vertx.executeBlocking(future -> {
vertx.eventBus().send("anAddress", inputString, event -> System.out.printf("got back from reply"));
future.complete();
}, res -> {
if (res.succeeded()) {
webSocketHandler.writeFinalTextFrame("output=" + inputString + "_result");
}
});
});
}).listen(8080);
}
@Override
public void stop() throws Exception {
super.stop();
}
}
EventBusReceiverVerticle:
public class EventBusReceiverVerticle extends AbstractVerticle {
private String name = null;
public EventBusReceiverVerticle(String name) {
this.name = name;
}
public void start(Future<Void> startFuture) {
vertx.eventBus().consumer("anAddress", message -> {
System.out.println(this.name +
" received message: " +
message.body());
try {
//doing some looong work..
Thread.sleep(10000);
System.out.printf("finished waiting\n");
startFuture.complete();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
我总是得到:
WARNING: Message reply handler timed out as no reply was received - it will be removed
github项目:https://github.com/IdanFridman/VertxAndWebSockets 谢谢, 射线。
答案 0 :(得分:0)
因为你阻止了你的websocket处理程序,直到收到对 EventBus 的已发送消息的回复,实际上,在 10s <的设置延迟之前不会收到回复/ strong>圈,你肯定会收到警告,因为事件总线的回复处理程序将超时 - &gt;发送消息但在超时延迟之前没有收到响应。
实际上我不知道您是否只是在试验 Vert.x 工具包,或者您正在尝试满足某些要求,但当然您必须调整代码以匹配 Vert.x 精神:
Thread.sleep(delay)
,即vertx.setTimer(...)
。