Client

package com.lgb.app.socket;


import android.content.Context;
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.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;


public class LgbClient {

private EventLoopGroup group;
private Context mContext;

public void connect(int port, String host, Context context) {
this.mContext = context;
System.out.println("客户端socket服务正在启动...");
group = new NioEventLoopGroup();

try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
//.option(ChannelOption.SO_BACKLOG, 2048)
       .option(ChannelOption.TCP_NODELAY, true)
       .option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChildChannelHandler());

ChannelFuture f = b.connect(host, port).sync();
if (f.isSuccess()) {
System.out.println("客户端socket服务启动成功...");
}

f.channel().closeFuture().sync();
System.out.println("客户端socket链路关闭...");
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("客户端socket shutdownGracefully...");
group.shutdownGracefully();
try {
Thread.sleep(60*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new LgbClient().connect(Constant.PORT, Constant.IP,this.mContext);
}
}

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new ProtobufVarint32FrameDecoder());
arg0.pipeline().addLast(new ProtobufDecoder(LgbMessage.Message.getDefaultInstance()));
arg0.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
arg0.pipeline().addLast(new ProtobufEncoder());
arg0.pipeline().addLast("idlehandler", new IdleStateHandler(60, 3, 0));//心跳监测
   arg0.pipeline().addLast(new LgbClientHandler(mContext));
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值