咱們在前面的章節中知道,ChannelHandler在ChannelPipeline中是有多個連接起來的,當咱們只想對某個ChannelHandler進行測試的時候,咱們能夠用特殊的Channel實現——EmbeddedChannel來達到咱們測試的目的。
主要的方法以下:segmentfault
// 將入站消息寫入到EmbeddedChannel中 public boolean writeInbound(Object... msgs) // 從EmbeddedChannel中讀取入站消息 public <T> T readInbound() // 將出站消息寫入到EmbeddedChannel中 public boolean writeInbound(Object... msgs) // 從EmbeddedChannel中讀取出站消息 public <T> T readOutbound() // 將EmbeddedChannel標記爲已完成 public boolean finish()
EmbeddedChannel的數據流
測試
FirstHandler和SecondHandler的代碼見以前的代碼spa
public static void main(String[] args) { testInbound(); testOutbound(); } public static void testOutbound() { System.out.println("----------------testOutbound----------------"); ByteBuf buf = Unpooled.buffer(); buf.writeBytes("hello".getBytes()); EmbeddedChannel channel = new EmbeddedChannel( new SecondHandler()); channel.writeOutbound(buf); ByteBuf o =channel.readOutbound(); System.out.println(o.toString(CharsetUtil.UTF_8)); } public static void testInbound() { System.out.println("----------------testInbound----------------"); ByteBuf buf = Unpooled.buffer(); buf.writeBytes("hello".getBytes()); EmbeddedChannel channel = new EmbeddedChannel( new FirstHandler()); channel.writeInbound(buf); ByteBuf o = channel.readInbound(); System.out.println(o.toString(CharsetUtil.UTF_8)); }
運行結果以下:
code