在上一篇文章中《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 {
-
- @Override
- public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
-
- sendObject(e.getChannel());
- }
-
- private void sendObject(Channel channel) {
- Command command = new Command();
- command.setActionName("Hello action.");
- channel.write(command);
- }
- }
3.再看一下服务端的代码
- public class ObjectServer {
- public static void main(String args[]) {
-
- ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
-
- 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());
- }
- }
先运行服务端,再运行客户端,然后在服务端的控制台中打印如下字符串
Android 基于Netty的消息推送方案之对象的传递(四)
原文:http://www.cnblogs.com/dongweiq/p/4019441.html