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();
}
2.CmdPipelineFactory:
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;
}
}
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);