android整合netty与protobuf

MotoAppClient的代码:

package com.hengzecn.nettyclient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

import com.hengzecn.protobuf.Auth;
/**
 * Created by nantongribao on 2017/4/24.
 */

public class MotoAppClient {
    public void connect(String host,int port) throws Exception{
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            Bootstrap b=new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //decoded
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                    ch.pipeline().addLast(new ProtobufDecoder(Auth.AuthResponse.getDefaultInstance()));
                    //encoded
                    ch.pipeline().addLast(new LengthFieldPrepender(4));
                    ch.pipeline().addLast(new ProtobufEncoder());
                    // ע��handler
                    ch.pipeline().addLast(new MotoAppClientHandler());
                }
            });
            ChannelFuture f=b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        }finally{
            workerGroup.shutdownGracefully();
        }
    }


}

MotoAppClientHandler的源码:

package com.hengzecn.nettyclient;

import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import com.hengzecn.protobuf.Auth;
/**
 * Created by nantongribao on 2017/4/24.x
 */

public class MotoAppClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Auth.AuthRequest request=Auth.AuthRequest.newBuilder()
                .setUserId("010203")
                .setPassword("abcde")
                .build();
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        Auth.AuthResponse response=(Auth.AuthResponse)msg;
        System.out.println("response: code="+response.getResultCode()+", message="+response.getResultMessage());
        ctx.close();
    }
}

MainActivity的源码:

package com.hengzecn.mototest.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.nantongribao.mototestclient.R;
import com.hengzecn.nettyclient.MotoAppClient;


public class MainActivity extends Activity {

    private Button mSendHeartBeat;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSendHeartBeat = (Button)findViewById(R.id.send_heart_beat);
        mSendHeartBeat.setOnClickListener(sendHeartBeatL);
    }

    private View.OnClickListener sendHeartBeatL = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "按钮按下",
                    Toast.LENGTH_SHORT).show();

            try {
                sendHeartBeat();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    };

    private void sendHeartBeat() throws Exception{
        new MotoAppClient().connect("129.0.5.11", 5555);
    }



}

调试通不过是因为没有为android开启internet访问权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nantongribao.mototestclient">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@mipmap/ic_launcher"
        android:allowBackup="true"
        android:theme="@android:style/Theme.Black.NoTitleBar">
        <activity
            android:name="com.hengzecn.mototest.activity.MainActivity"
             >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

 

转载于:https://my.oschina.net/u/438393/blog/886781

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值