package com.example.demo.client1;
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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* LineBasedFrameDecoder半包处理
* @author 程就人生
* @date 2019年10月26日
*/
public class LinebaseClient {
public void connect(int port, String host){
//客户端Nio线程组
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap bootstrap = new Bootstrap();
//线程组设置为非阻塞
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//和服务器端保持一致
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new LinebaseClientHandler());
}
});
//建立连接
ChannelFuture channelFuture = bootstrap.connect(host, port);
//等待服务端监听端口关闭
channelFuture.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
}finally{
//优雅退出
group.shutdownGracefully();
}
}
public static void main(String[] argo){
new LinebaseClient().connect(8080, "localhost");
}
}
最近下载更多
最近浏览更多
1909741473 LV8
2024年2月19日
sunlzh888888 LV29
2023年9月12日
微信网友_6491062177157120
2023年5月25日
暂无贡献等级
yinyun1985 LV14
2022年10月31日
youwuzuichen LV11
2022年10月28日
1358849392 LV21
2022年10月21日
Killah LV9
2022年9月5日
no1xijin
2022年8月1日
暂无贡献等级
林间听风 LV10
2022年4月11日
xp95323 LV15
2022年1月25日

