在上一篇文章中《Android 基于Netty的消息推送方案之字符串的接收和发送(三)》我们介绍了Netty的字符串传递,我们知道了Netty的消息传递都是基于流,通过ChannelBuffer传递的,那么自然,Object也须要转换成ChannelBuffer来传递。好在Netty本身已经给我们写好了这种转换工具。ObjectEncoder和ObjectDecoder,以下我们介绍一个案例。
1. 我们构造一个用来传输的对象(JavaBean)
@SuppressWarnings("serial") public class Command implements Serializable { private String actionName; public String getActionName() { return actionName; } public void setActionName(String actionName) { this.actionName = actionName; } }
2.我们先看一下Client的代码
public class ObjectClient { public static void main(String args[]) { ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new ObjectEncoder(), new ObjectClientHandler()); } }); bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000)); } } class ObjectClientHandler extends SimpleChannelHandler { /** * 当绑定到服务端的时候触发,给服务端发消息。3.再看一下服务端的代码*/ @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // 向服务端发送Object信息 sendObject(e.getChannel()); } /** * 发送Object * @param channel */ private void sendObject(Channel channel) { Command command = new Command(); command.setActionName("Hello action."); channel.write(command); } }
public class ObjectServer { public static void main(String args[]) { // Server服务启动器 ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // 设置一个处理client消息和各种消息事件的类(Handler) bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { //先编码 --> 后处理自己的业务 return Channels.pipeline(new ObjectDecoder(ClassResolvers.cacheDisabled(this.getClass().getClassLoader())), new ObjectServerHandler()); } }); bootstrap.bind(new InetSocketAddress(8000)); } } class ObjectServerHandler extends SimpleChannelHandler { /** * 当接受到消息的时候触发 */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Command command = (Command) e.getMessage(); // 打印看看是不是我们刚才传过来的那个 System.out.println(command.getActionName()); } }先执行服务端,再执行client,然后在服务端的控制台中打印例如以下字符串
Hello action.