【问题标题】:Using Netty ( tcp ), sending message from client in android to server使用 Netty ( tcp ),将消息从 android 中的客户端发送到服务器
【发布时间】:2014-02-27 00:24:40
【问题描述】:

我在android和服务器中成功连接了bitween客户端。

但是,当我想发送诸如“你好”之类的消息时,消息消失了。

这是我的客户代码:

group = new OioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(OioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(handler);
        }
    });

    Channel ch = null;
    ChannelFuture f = null;
    try {
        f = b.connect(new InetSocketAddress(host, port)).sync();
        ch = f.channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    ch.writeAndFlush("hello!");

这是我的服务器代码:

@Override
public void channelActive(ChannelHandlerContext ctx){
    channels.add(ctx.channel());
    ctx.channel().writeAndFlush("Welcome My Server");
    System.out.println(ctx.channel().remoteAddress());
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

当我连接时,服务器正在打印“连接的客户端 IP 地址” 但在那之后,“你好”消息不会打印在我的服务器上。 怎么了?服务器?客户? 我认为编码,解码没有问题,因为没有收到 请告诉我该怎么做?

【问题讨论】:

    标签: android tcp netty


    【解决方案1】:

    如果你想写一个字符串,你需要把 StringEncoder 放在 ChannelPipeline 中(在客户端)。如果你检查 writeAndFlush(...) 返回的 ChannelFuture,你会发现它失败了。

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 2013-04-29
      • 2012-12-05
      • 2012-10-04
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2017-09-15
      相关资源
      最近更新 更多