客户端的这部份代码跟服务器端差不多,就不另开一文啰嗦了。之间帖代码:
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; public class NettyClient { public void sendMsgToServer() throws Exception{ EventLoopGroup group = new NioEventLoopGroup(); try{ //设置辅助启动类信息 Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class)//选择channel类型 .option(ChannelOption.TCP_NODELAY, true) .handler(new childChannelHandler()); //阻塞等待成功连接服务器 ChannelFuture channelFuture = bootstrap.connect(localhost,8000).sync(); //阻塞等待来自服务器的处理结果 channelFuture.channel().closeFuture().sync(); }finally{ group.shutdownGracefully(); } } private class childChannelHandler extends ChannelInitializer{ @Override protected void initChannel(SocketChannel ch) throws Exception { //TODO 添加其他功能处理Handler,如消息加解密 ch.pipeline().addLast(new NettyClientHandler()); } } }