客户端代码:
public class TCPClient {
public void connect(int port,String host)throws Exception{
//网络事件处理线程组
EventLoopGroup group=new NioEventLoopGroup();
try{
//配置客户端启动类
Bootstrap b=new Bootstrap();
b.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 DealMsg());//设置自定义解码器
ch.pipeline().addLast(new TCPClientHandler());//设置客户端网络IO处理器
}
});
//连接服务器 同步等待成功
ChannelFuture f=b.connect(host,port).sync();
//同步等待客户端通道关闭
f.channel().closeFuture().sync();
}finally{
//释放线程组资源
group.shutdownGracefully();
}
}
}
客户端handler
public class TCPClientHandler extends ChannelHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("通信异常!!");
cause.printStackTrace();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("链接服务端成功!");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("退出链接!!");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("接受服务器数据:=="+msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.channel().writeAndFlush("数据读取完成!");
}
}