客戶端代碼:
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.remoteAddress("localhost", 7113)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInboundHandlerAdapter(){
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(">>>>> 消息發送..");
ctx.channel().writeAndFlush("sasaas");
}
});
try {
Channel channel = bootstrap.connect().sync().channel();
ChannelFuture future = channel.closeFuture().sync();
future.addListener(ChannelFutureListener.CLOSE);
} catch (InterruptedException e) {
} finally {
group.shutdownGracefully();
}
}
}
服務端代碼:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NettyServer {
public static void main(String[] args) {
ServerBootstrap bootstrap = new ServerBootstrap();
EventLoopGroup group = new NioEventLoopGroup();
bootstrap.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new LoggingHandler(LogLevel.DEBUG));
try {
ChannelFuture future = bootstrap.bind(7113).sync();
future = future.channel().closeFuture().sync();
} catch (InterruptedException e) {
} finally {
group.shutdownGracefully();
}
}
}
日誌:
client 日誌>>>>> 消息發送..
server 日誌>>>>
原因:
最後傳輸的消息是bytebuf 或 fileRegion,其他消息不進行發送