站务联系

Netty从没听过到入门 -- 服务器端详解(3)

发布时间:2021-03-31   来源:网络整理    
字号:

客户端的这部份代码跟服务器端差不多,就不另开一文啰嗦了。之间帖代码:

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());
        }
    }
}

图说天下

  • 3页:
  • 上一页
  • 1
  • 2
  • 3
  • 下一页
  • ×
    二维码生成