Android 基于Netty的消息推送方案之字符串的接收和发送(三)

在上一篇文章中Android 基于Netty的消息推送方案之概念和工作原理(二) ,我们介绍过一些关于Netty的概念和工作原理的内容,今天我们先来介绍一个叫做ChannelBuffer的东东。

ChannelBuffer


 Netty中的消息传递,都必须以字节的形式,以ChannelBuffer为载体传递。简单的说,就是你想直接写个字符串过去,对不起,抛异常。虽然,Netty定义的writer的接口参数是Object的,这可能也是会给新上手的朋友容易造成误会的地方。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()));
		//设置一个处理客户端消息和各种消息事件的类(Handler)
		bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new BusinessHandler());
			}			
		});
		//开放8000端口供客户端连接
		bootstrap.bind(new InetSocketAddress(8000));
	}
	
	private static class BusinessHandler extends SimpleChannelHandler{
		// 服务端收到客户端发送过来的消息时,触发此方法
		@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);
        }
	}
}
客户端代码如下

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);
		}
	}
}

先启动服务端,再启动客户端,可以看到服务端打印如下字符串

Receive:Hello, I'm client.




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。