this.channel = channel;
}
public ClientBootstrap getBootstrap() {
return bootstrap;
}
public void setBootstrap(ClientBootstrap bootstrap) {
this.bootstrap = bootstrap;
}
public ChannelFuture getChannelFuture() {
return channelFuture;
}
public void setChannelFuture(ChannelFuture channelFuture) {
this.channelFuture = channelFuture;
}
public int start(String ip,int port) {
System.setProperty(“java.net.preferIPv4Stack”, “true”);
System.setProperty(“java.net.preferIPv6Addresses”, “false”);
bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new CmdPipelineFactory());
bootstrap.setOption(“tcpNoDelay”, true);
bootstrap.setOption(“keepAlive”, true);
channelFuture = bootstrap.connect(new InetSocketAddress(ip, port));
channelFuture.awaitUninterruptibly();
channel = channelFuture.awaitUninterruptibly().getChannel();
return 1;
}
public void stop() {
channelFuture.awaitUninterruptibly();
if (!channelFuture.isSuccess()) {
channelFuture.getCause().printStackTrace();
}
channelFuture.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
}
public class CmdPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast(“cmdDecoder”, new CmdDecoder());
pipeline.addLast(“handler”, new CmdClientHandler());
return pipeline;
}
}
[](https://blog.csdn.net/fjnu_se/article/details
/90757870)3.引入CmdDecoder用来解析协议
public class CmdDecoder extends FrameDecoder {
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer buffer) throws Exception {
if (buffer.readableBytes() < 1) {
return null;
}
buffer.markReaderIndex();
ChannelBuffer magicBuff = buffer.readBytes(1);
int magic = DataConvert.byteArrayToSignedInt(magicBuff
.array());
if (magic == 0x77) {
if (buffer.readableBytes() < 19) {
return null;
}
buffer.markReaderIndex();
ChannelBuffer lenBuff = buffer.readBytes(19);
PacketParse parse = new PacketParse(null);
byte[] lenByte = parse.getPackForTwoByte(lenBuff.array(), 17, 2);
int len = DataConvert.byteArrayToSignedInt(lenByte);
if (buffer.readableBytes() < len) {
buffer.resetReaderIndex();
最后
小编这些年深知大多数初中级Android工程师,想要提升自己,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人
都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
资料⬅专栏获取
是希望能够帮助到想自学提升又不知道该从何学起的朋友。**
[外链图片转存中…(img-WQCZ2x0r-1718821968246)]
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人
都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
资料⬅专栏获取