当前位置: 首页 > 知识库问答 >
问题:

无法使用Netty将字节[]发送到服务器

濮升
2023-03-14

我对妮蒂很陌生。我目前正在编写一个非常简单的Echo客户端和服务器,但是我尝试从客户端向服务器发送< code>byte[]而不是String或ByteBuf。我成功地用字符串消息编写了相同的客户机\服务器。

在相同的代码中,我只是将“解码器\编码器”改为使用< code>byte[]。

我在下面张贴我的代码。

EchoClient。java-启动客户端的主类

public class EchoClient {

    private final String host;
    private final int port;
    private final int firstMessageSize;

    public EchoClient(String host, int port, int firstMessageSize) {
        this.host = host;
        this.port = port;
        this.firstMessageSize = firstMessageSize;
    }

    public void run() throws Exception {
        // Configure the client.
        String firstTestMessage = "Avinash \r\n";
        byte[] bytes = firstTestMessage.getBytes("UTF-8");

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new EchoClientByteHandler(bytes));

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        // Print usage if no argument is specified.

        args = new String[2];
        args[0] = "localhost";
        args[1] = "9090";
        if (args.length < 2 || args.length > 3) {
            System.err.println("Usage: " + EchoClient.class.getSimpleName()
                    + " <host> <port> [<first message size>]");
            return;
        }

        // Parse options.
        final String host = args[0];
        final int port = Integer.parseInt(args[1]);
        final int firstMessageSize;
        if (args.length == 3) {
            firstMessageSize = Integer.parseInt(args[2]);
        } else {
            firstMessageSize = 5;
        }

        new EchoClient(host, port, firstMessageSize).run();
    }
}

EchoClientByteInitialzer - Define pipeline

public class EchoClientByteInitialzer extends ChannelInitializer<SocketChannel>{

    private byte[] mBytes = null;

    public EchoClientByteInitialzer(byte[] bytes)
    {
        this.mBytes = bytes;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
        pipeline.addLast("bytesDecoder", new ByteArrayDecoder());

        // Encoder
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        pipeline.addLast("bytesEncoder", new ByteArrayEncoder());

        pipeline.addLast("handler", new EchoClientByteHandler(mBytes));
    }

}

EchoClientByteHandler - 主客户端处理程序

public class EchoClientByteHandler extends ChannelInboundHandlerAdapter {
    private byte[] mBytes = null;

    public EchoClientByteHandler(byte[] bytes) {
        this.mBytes = bytes;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(mBytes);
        System.out.println(mBytes);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ctx.write(msg);
        System.out.println(msg);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

EchoServer-启动服务器的主类

public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new EchoServerByteInitialzer());

            // Start the server.
            ChannelFuture f = b.bind(port).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 9090;
        }
        new EchoServer(port).run();
    }
}

EchoServerLaunalizer-服务器的管道

public class EchoServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel arg0) throws Exception {
        ChannelPipeline ch = arg0.pipeline();

        ch.addLast(
                "farmer",
                new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

        ch.addLast("decoder", new StringDecoder());

        ch.addLast("encoder", new StringEncoder());

        ch.addLast("handler",new EchoServerHandler());

    }

}

回显服务器处理程序 - 主服务器处理程序

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = Logger
            .getLogger(EchoServerHandler.class.getName());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        try {
            ctx.write(msg);
            System.out.println(msg);

        } finally {

        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        logger.log(Level.WARNING, "Unexpected exception from downstream.",
                cause);
        ctx.close();
    }
}

请建议我这里缺少什么。

共有1个答案

孟均
2023-03-14

我刚刚升级到netty4.0.18.jar,事情开始对我有用。我不知道netty4.0.17.jar出了什么问题,但它正在netty4.0.18.jar

 类似资料:
  • 我正在试用netty,但当我响应时,客户端似乎没有收到我的消息。我使用Java NIO和socketChannel编写了相同的代码,看起来很好。我这样说是因为客户机会记录我发送的任何内容。下面是我的服务器 下面是我的服务器处理程序 } 示例响应: 我正在我的盒子上做一个tcpdump,我看到了我在电线上发送的内容,所以我不确定我做错了什么。而且,几分钟后,这会被记录下来,我不确定我在服务器或服务器

  • 问题内容: 我正在尝试创建一个群集以将消息发送到远程控制。我已经按照此处所述配置了所有内容。我正在机器上运行它,并且使用shell可以正常工作。在Windows计算机上按照教程中的说明编写Java代码后,我收到以下错误: 我也尝试在其他Linux机器上运行jar,但仍然收到相同的错误。 可以在安装kafka的计算机中将地址更改为jar并在其中运行Java代码。 我相信它与配置有关,但是找不到。 问

  • 问题内容: 我想通过齐射库 {“ user_id”:12,“ answers”:{“ 11”:3,“ 12”:4,“ 13”:5}}* 将以下格式的jsonobject发送到服务器 * 如果我想使用 StringRequest, 如何使用POST方法将此JsonObject发送到服务器 问题答案: 您可以使用以下工作示例代码。我测试过了 希望这可以帮助! 更新: 要创建JSONObject作为您的

  • 我必须向服务器发送一个映像(我认为最好的选择是使用HttpURLConnection)并从它接收一个字符串答案。在我读过的不同的文档和web站点中,我研究了这样做的最佳方法是使用多伙伴关系。 1_做它是最好的解决方案吗? 2_我有一个错误,说Android Studio无法解析符号'multipartentity'。我读到,要解决它,我必须下载外部库。哪些是它们,我如何下载它们? 3_为此,我想在

  • 问题内容: 我有一个REST Web服务配置如下: 我的Tomcat服务器的配置如下: 我创建的POJO如下所示: } 我创建一个测试客户端以测试createUser方法: 但是我收到以下错误: 奇怪的是,当我将所有内容更改为appliction / xml时,它都能正常工作 知道为什么Json不能为我工作吗? 问题答案: 您正在执行: 这是不对的。您应该将真实的JSON字符串发送到您的服务。 获

  • 我正在使用新的Firebase平台。我试图让我的应用程序服务器发送消息推送到我的iPhone。 我的设置正在运行,我在网站上的Firebase通知区域手动发送消息,但当我尝试将消息发送到https://fcm.googleapis.com/fcm/send 我没有收到发送到设备的消息。 我正在发送以下内容(带有auth头) 我从POST得到了200个响应,有以下身体: 如果我尝试直接通过Fireb