Netty 检测通道组中的通道连接关闭
根据这段代码(来自netty示例),我想实现presence系统。因此,我需要检测clientconnection何时丢失(例如,由于客户端internet捆绑包已完成)Netty 检测通道组中的通道连接关闭,netty,Netty,根据这段代码(来自netty示例),我想实现presence系统。因此,我需要检测clientconnection何时丢失(例如,由于客户端internet捆绑包已完成) 公共类SecureChatServerHandler扩展了SimpleChannelInboundHandler{ 静态最终通道组通道=新的DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @凌驾 公共无效通道激活(最终通道HandlerContext ctx){ ctx.p
公共类SecureChatServerHandler扩展了SimpleChannelInboundHandler{
静态最终通道组通道=新的DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@凌驾
公共无效通道激活(最终通道HandlerContext ctx){
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
新的GenericFutureListener(){
@凌驾
public void operation complete(未来)引发异常{
ctx.writeAndFlush(
“欢迎使用”+InetAddress.getLocalHost().getHostName()+“安全聊天服务!\n”);
ctx.writeAndFlush(
“您的会话受”+
ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()+
“密码套件。\n”);
channels.add(ctx.channel());
}
});
}
@凌驾
public void channelRead0(ChannelHandlerContext ctx,String msg)引发异常{
//将收到的消息发送到除当前通道外的所有通道。
用于(通道c:通道){
如果(c!=ctx.channel()){
c、 writeAndFlush(“[”+ctx.channel().remoteAddress()+“]”+msg+'\n');
}否则{
c、 writeAndFlush(“[you]”+msg+'\n');
}
}
//如果客户端已发送“再见”,请关闭连接。
if(“bye”.equals(msg.toLowerCase())){
ctx.close();
}
}
---
}
频道关闭时如何通知频道组?
示例来源:解决此问题的一种方法是在处理程序中使用函数 当通道因成功关闭或网络错误而关闭时,调用此函数
@覆盖
public void channelInactive(ChannelHandlerContext ctx)引发异常{
//将收到的消息发送到除当前通道外的所有通道。
用于(通道c:通道){
如果(c!=ctx.channel()){
c、 writeAndFlush(“[”+ctx.channel().remoteAddress()+“]已离开聊天室\n”);
}
}
}
public class SecureChatServerHandler extends SimpleChannelInboundHandler<String> {
static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void channelActive(final ChannelHandlerContext ctx) {
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
ctx.writeAndFlush(
"Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
ctx.writeAndFlush(
"Your session is protected by " +
ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
" cipher suite.\n");
channels.add(ctx.channel());
}
});
}
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// Send the received message to all channels but the current one.
for (Channel c: channels) {
if (c != ctx.channel()) {
c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
} else {
c.writeAndFlush("[you] " + msg + '\n');
}
}
// Close the connection if the client has sent 'bye'.
if ("bye".equals(msg.toLowerCase())) {
ctx.close();
}
}
---
}