jboss的netty中下游事件是如何工作的?
刚刚开始使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您拥有对 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).