2014-02-27 54 views
0

我成功連接位於android和服務器端的客戶端。使用Netty(tcp),發送消息從客戶端在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); 
    } 
} 

當我連接,服務器正在打印 '連接的客戶端IP地址' 但在此之後,「你好「的消息不會打印在我的服務器上。 有什麼問題?服務器?客戶? 我認爲編碼,解碼不是問題,因爲沒有收到 請讓我知道該怎麼做?

回答

0

如果你想寫一個字符串,你需要把StringEncoder放在ChannelPipeline(在客戶端)。如果你檢查writeAndFlush(...)返回的ChannelFuture,你會發現它失敗了。

相關問題