服务端代码(解释以注释的形式体现):
设置步骤:线程模型、IO模型,IO业务处理逻辑,连接
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class NettyClient {
public static final AttributeKey<String> CLIENT_NAME = AttributeKey.newInstance("clientName");
public static void main(String[] args) {
NioEventLoopGroup group=new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap()
// 1.指定线程模型
.group(group)
// 2.指定 IO 类型为 NIO
// 指定服务端所用的IO模型:NioSocketChannel.class为NIO,OioSocketChannel.class为BIO
// 参数NioSocketChannel是对NIO类型的连接的抽象,可以和BIO编程模型中的Socket概念对应上
.channel(NioSocketChannel.class)
//4 给客户端的NioSocketChannel连接指定自定义属性,然后后续可以通过channel.attr()取出该属性
// 注意把key使用静态变量存,否则会出现IllegalArgumentException: 'xxx' is already in use netty
.attr(CLIENT_NAME,"nettyClient")
// 3.IO处理逻辑
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
//取出.attr()绑定的自定义属性
System.out.println(".attr()绑定的数据为:"+ch.attr(CLIENT_NAME).get());
ch.pipeline().addLast(new StringEncoder());
}
})
//给连接设置一些 TCP 底层相关的属性
//表示连接的超时时间,超过这个时间还是建立不上的话则代表连接失败
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
//表示是否开启 TCP 底层心跳机制,true 为开启
.option(ChannelOption.SO_KEEPALIVE, true)
//表示是否开始 Nagle 算法,true 表示关闭,false 表示开启
//如果要求高实时性,有数据发送时就马上发送,就设置为 true 关闭,如果需要减少发送次数减少网络交互,就设置为 false 开启
.option(ChannelOption.TCP_NODELAY, true);
// 4.建立连接,如果失败者2秒后重试
connect(bootstrap);
}
private static void connect(Bootstrap bootstrap) {
ChannelFuture channelFuture =bootstrap.connect(new InetSocketAddress("127.0.0.1", 9999));
channelFuture.addListener(future -> {
if(future.isSuccess()) {
System.out.println("连接成功");
hello(channelFuture);
return;
}else {
System.out.println("连接失败!2秒后重试...");
bootstrap.config().group().schedule(() -> connect(bootstrap), 2, TimeUnit.SECONDS);
}
});
}
private static void hello(ChannelFuture channelFuture) {
System.out.println("业务逻辑执行");
Channel channel =channelFuture.channel();
while (true){
channel.writeAndFlush(new Date() + ": hello world!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}