Netty:立即发送消息并在客户端连接时等待响应

Netty: Immediately send a message and expect for a response when the clients become connected

这是我第一次使用Netty,我设法让我的服务器和客户端一起工作。

现在我想在上面添加安全性,服务器正在等待传入的客户端 接受后,服务器将在几秒钟内发送一条消息并期待响应。 然后,如果客户端没有响应,它会被服务器自动断开连接。怎么做?

EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
    ServerBootstrap b = new ServerBootstrap(); // (2)
    b.group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class) // (3)
    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ServerHandler());
    }
    }).option(ChannelOption.SO_BACKLOG, 128)          // (5)
    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

    // Bind and start to accept incoming connections.
    Log.w(TAG,"SERVER started, waiting for incoming clients...");
    ChannelFuture f = b.bind(port).sync(); // (7)

    //Immediately send message to the client, but this failed
    Channel channel = f.awaitUninterruptibly().channel();
    channel.writeAndFlush("passsword?\n");
    /** Expect response from client here... but how???  **/


    f.channel().closeFuture().sync();
} catch (Exception e){
    Log.e(TAG,"SERVER Exception, >> " + e.toString());
}finally {
    workerGroup.shutdownGracefully();
    bossGroup.shutdownGracefully();
    Log.w(TAG,"SERVER finally Stopped.");
}

我什至尝试在接受客户后使用 channel.writeAndFlush("passsword?\n"); 发送消息,但客户没有收到任何消息。 有什么想法吗?

我认为您弄错了通道绑定操作 returns 不是客户端通道,它是管理客户端通道(接受新连接等)的服务器通道。

如果您想在客户端连接后发送一个数据包,您需要在您的客户端处理程序之一的 channelActive 方法中发送它。 (在您的示例中是 ServerHandler)

关于netty状态系统的更多信息我准备了这张图:

举个例子:

public class FooHandler extends SimpleChannelInboundHandler<Bar> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ctx.channel().writeAndFlush("HELLO:PASSWORD");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Bar bar) throws Exception {
        //do stuff
    }
}

希望有所帮助