channelInboundHandler中的channelActive方法发送消息的问题

新手上路,请多包涵

1、在channelActive方法中调用writeAndFlush()方法发送消息的时候,为什么在之前的线程中调用会发送不出去呢?(也不会报错):
@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    SocketAddress socketAddress = channel.remoteAddress();
    // 添加
    Global.group.add(channel);
    Global.group.writeAndFlush(new TextWebSocketFrame("entry to chat"));
    System.out.println("client and server start connect:" + socketAddress.toString());
}

2、如果我把这里的方法改成异步执行,就会发送出去:
@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    SocketAddress socketAddress = channel.remoteAddress();
    // 添加
    Global.group.add(channel);
    TextWebSocketFrame frame = new TextWebSocketFrame("entry to chat");
    new Thread(() -> Global.group.writeAndFlush(frame)).start();
    System.out.println("client and server start connect:" + socketAddress.toString());
}

3、如果同时存在同步和异步两种调用的话,也不会有消息发送出去。
这个是什么问题呢?

阅读 5.9k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题