我在android和服务器中的客户端之间成功连接。
但是,当我想发送“hello”等消息时,消息就消失了。
这是我的客户代码:
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);
}
}
当我连接时,Server正在打印'连接的客户端IP地址' 但之后,我的服务器中没有打印“你好”的消息。 怎么了?服务器?客户? 我认为编码,解码不是问题,因为没有收到 请让我知道如何做到这一点?
答案 0 :(得分:0)
如果要编写String,则需要将StringEncoder放在ChannelPipeline中(在客户端)。如果你检查返回的writeAndFlush(...)的ChannelFuture,你会发现它失败了。