在上一篇文章中《Android 基于Netty的消息推送方案之概念和工作原理(二)》 。我们介绍过一些关于Netty的概念和工作原理的内容,今天我们先来介绍一个叫做ChannelBuffer的东东。
ChannelBuffer
Netty中的消息传递,都必须以字节的形式,以ChannelBuffer为载体传递。
简单的说,就是你想直接写个字符串过去,对不起,抛异常。尽管,Netty定义的writer的接口參数是Object的,这可能也是会给新上手的朋友easy造成误会的地方。
Netty源代码中。是这样推断的。
SendBuffer acquire(Object message) { if (message instanceof ChannelBuffer) { return acquire((ChannelBuffer) message); } else if (message instanceof FileRegion) { return acquire((FileRegion) message); } throw new IllegalArgumentException( "unsupported message type: " + message.getClass()); }接下来我们写一个Demo来学习它。
服务端代码例如以下
public class MessageServer { public static void main(String args[]){ //服务启动器 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 BusinessHandler()); } }); //开放8000port供client连接 bootstrap.bind(new InetSocketAddress(8000)); } private static class BusinessHandler extends SimpleChannelHandler{ // 服务端收到client发送过来的消息时,触发此方法 @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer buffer = (ChannelBuffer)e.getMessage(); System.out.println("Receive:"+buffer.toString(Charset.defaultCharset())); String msg = buffer.toString(Charset.defaultCharset()) + "has been processed!"; ChannelBuffer buffer2 = ChannelBuffers.buffer(msg.length()); buffer2.writeBytes(msg.getBytes()); e.getChannel().write(buffer2); } } }client代码例如以下
public class MessageClient { 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 MessageClientHandler()); } }); bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000)); } private static class MessageClientHandler extends SimpleChannelHandler { /** * 当绑定到服务端的时候触发,给服务端发消息。 */ @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // 将字符串,构造成ChannelBuffer,传递给服务端 String msg = "Hello, I'm client."; ChannelBuffer buffer = ChannelBuffers.buffer(msg.length()); buffer.writeBytes(msg.getBytes()); e.getChannel().write(buffer); } } }
先启动服务端,再启动client,能够看到服务端打印例如以下字符串
Receive:Hello, I'm client.
假设你感兴趣,请继续阅读《Android 基于Netty消息传递的对象推送方案(四)》
版权声明:本文博主原创文章,博客,未经同意不得转载。