jboss的netty中下游事件是如何工作的?

发布于 2024-09-10 01:28:38 字数 529 浏览 8 评论 0原文

刚刚开始使用 netty 来实现我自己的服务器。我花了一段时间才掌握它的窍门,但现在我能够通过编写自己的 MessageHandler 来接受客户端,并且在 messageReceived 中我能够从缓冲区中读取数据并执行一些与接收到的数据相关的业务逻辑。

但现在的问题是,如何将数据写入连接的客户端?我看到了示例代码,您可以在出现这样的新消息时写入通道:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Channel ch = e.getChannel();
    ch.write(e.getMessage());
}

但是如果您不想在此时写回数据怎么办?如果客户端在套接字中保持连接并等待服务器中发生某些事件怎么办?在这种情况下,我的服务器将如何找到正确的套接字进行写入?我应该保留对通道对象的引用吗?这是约定吗?

我进一步查看代码,看到了一个名为 writeRequested 的方法。这有关系吗?谁这么称呼的?以及有必要吗?

Just started playing around with netty in implementing my own server. Took me a while to get the hang of it but now I was able to accept clients by writing my own MessageHandler and inside messageReceived I was able to read from the buffer and did some business logic related to the data received.

However the question now is, how do I write data into connected clients? I saw the sample code where you can write to the channel in the event of a new message like this:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Channel ch = e.getChannel();
    ch.write(e.getMessage());
}

but what if you don't want to write the data back at that point? What if the client stays connected in the socket and waits until some event occurs in the server? In that case how will my server find the right socket to write to? Am I suppose to keep a reference to the channel object? Is this the convention?

I looked further into the code and saw a method called writeRequested. Is that related? Who calls that? And is it needed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想念有你 2024-09-17 01:28:38

只要您拥有对 Channel(或 ChannelHandlerContext)的引用,您就可以从任何地方、任何线程调用 Channel.write()(或 Channels.write())。

当您通过调用 Channel.write() 或调用 ChannelHandlerContext.sendDownstream(MessageEvent) 触发 writeRequested 事件时,将调用 writeRequested()。

As long as you have the reference to the Channel (or ChannelHandlerContext), you can call Channel.write() (or Channels.write()) from anywhere, any thread.

writeRequested() is called when you trigger the writeRequested event by calling Channel.write() or calling ChannelHandlerContext.sendDownstream(MessageEvent).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文