2017-04-30 1703 views
0

我正在使用Netty 4.1.9編寫服務器客戶端應用程序。Netty - 發送失敗:UnsupportedOperationException:不支持的消息類型

最近我成功地使用ByteBuf進行通信。 然後用String嘗試並再次成功。

但隨着最後一步,我想發送自定義對象,並有我的問題:

Send failed: java.lang.UnsupportedOperationException: unsupported message type: GIdPacket (expected: ByteBuf, FileRegion) 

某些代碼部分

服務器:

ServerBootstrap b = new ServerBootstrap(); 
b.group(bossGroup, workerGroup) 
    .channel(NioServerSocketChannel.class) 
    .childHandler(new ChannelInitializer<SocketChannel>() { 
     @Override 
     public void initChannel(SocketChannel ch) throws Exception { 
      ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null))); 
      ch.pipeline().addLast(new ObjectEncoder()); 
      ch.pipeline().addLast(new ServerHandler()); 
      ch.pipeline().addLast(loggingHandler); 
     } 
    }) 
    .option(ChannelOption.SO_BACKLOG, 128) 
    .childOption(ChannelOption.SO_KEEPALIVE, true) 
    .option(ChannelOption.AUTO_READ, true); 

ChannelFuture f = b.bind(port).sync(); 

ServerHandler:

@Override 
public void channelActive(ChannelHandlerContext ctx) throws Exception 
{ 
    System.out.println("CHANNEL >> channelActive fired"); 
    clientData = new ClientData(Server.newId(), ctx.channel()); 
    Server.clients.put(clientData.id, clientData); 

    GIdPacket packet = new GIdPacket(/*some init atr*/); 

    ChannelFuture cf = ctx.writeAndFlush(packet); 
    if (!cf.isSuccess()) { 
     System.out.println("Send failed: " + cf.cause()); 
    } 

    Log.out(packet.toString()); 
} 

所以,我嘗試了很多不同的選擇。我花了很多時間,我沒有找到解決辦法。任何幫助讚賞。

回答

1

看起來像GIdPacket沒有實現Serializable接口。根據文檔,ObjectEncoder僅支持可序列化的對象:class ObjectEncoder extends MessageToByteEncoder<Serializable>

順便說一下,您正試圖在執行writeAndFlush(..)後立即檢查channelFuture.isSuccess()。因爲Netty完全異步,所以此測試將失敗,因爲channelFuture既不成功也不失敗。您必須等到CF完成後才致電cf.await()cf.awaitUninterruptibly()

+0

所以就像你說的,我讓我的對象可序列化,它現在可以工作。 Grats! – Shaq

+0

千萬不要在EventLoop線程中調用'cf.await *'。你應該註冊一個未來的聽衆。 –

相關問題