標籤:android blog http io os ar java for strong
在上一篇文章中《Android 基於Netty的訊息推送方案之字串的接收和發送(三)》我們介紹了Netty的字串傳遞,我們知道了Netty的訊息傳遞都是基於流,通過ChannelBuffer傳遞的,那麼自然,Object也需要轉換成ChannelBuffer來傳遞。好在Netty本身已經給我們寫好了這樣的轉換工具。ObjectEncoder和ObjectDecoder,下面我們介紹一個案例。
1. 我們構造一個用來傳輸的對象(JavaBean)
[java] view plaincopy
- @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的代碼
[java] view plaincopy
- 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) {
- // 向服務端發送Object資訊
- sendObject(e.getChannel());
- }
- /**
- * 發送Object
- * @param channel
- */
- private void sendObject(Channel channel) {
- Command command = new Command();
- command.setActionName("Hello action.");
- channel.write(command);
- }
- }
3.再看一下服務端的代碼
[java] view plaincopy
- public class ObjectServer {
- public static void main(String args[]) {
- // Server服務啟動器
- 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 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());
- }
- }
先運行服務端,再運行用戶端,然後在服務端的控制台中列印如下字串
[java] view plaincopy
- Hello action.
Android 基於Netty的訊息推送方案之對象的傳遞(四)