Netty 是基于NIO封装的网络通信库,相较于Java原生IO库来说具有以下优点
推荐文章:https://segmentfault.com/a/1190000007282628
<dependency>
<groupId>io.nettygroupId>
<artifactId>netty-allartifactId>
<version>4.1.43.Finalversion>
dependency>
compile 'io.netty:netty-all:4.1.43.Final'
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Description: Netty 简单服务端示例
*
* Date: 2019/12/27 1:42
*
* @author ALion
*/
public class SimpleServer {
public static void main(String[] args) {
// linux 下建议使用 EpollEventLoopGroup
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleServerHandler());
}
});
try {
ChannelFuture future = bootstrap.bind(23333).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
* Description: Netty 简单服务器的处理器
*
* Date: 2019/12/27 1:44
*
* @author ALion
*/
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleServerHandler.channelRead");
ByteBuf buf = (ByteBuf) msg;
System.out.println("Server received: " + buf.toString(CharsetUtil.UTF_8));
ByteBuf byteBuf = Unpooled.copiedBuffer("happy", CharsetUtil.UTF_8);
ctx.writeAndFlush(byteBuf);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import java.util.Scanner;
/**
* Description: Netty 简单客户端示例
*
* Date: 2019/12/27 1:48
*
* @author ALion
*/
public class SimpleClient {
public static void main(String[] args) {
// linux 下建议使用 EpollEventLoopGroup
EventLoopGroup loopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap()
.group(loopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleClientHandler());
}
});
try {
ChannelFuture future = bootstrap.connect("127.0.0.1", 23333).sync();
Channel channel = future.channel();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
String s = scanner.nextLine();
ByteBuf byteBuf = Unpooled.copiedBuffer(s, CharsetUtil.UTF_8);
channel.writeAndFlush(byteBuf);
}
future.channel().close();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
loopGroup.shutdownGracefully();
}
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
* Description: Netty 简单客户端的处理器
*
* Date: 2019/12/27 1:50
*
* @author ALion
*/
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleClientHandler.channelRead");
ByteBuf buf = (ByteBuf) msg;
System.out.println("Client received: " + buf.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
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;
/**
* Description: Netty 聊天服务器示例
*
* Date: 2019/12/16 3:19
*
* @author ALion
*/
public class MyChatServer {
public static void main(String[] args) {
// linux 下建议使用 EpollEventLoopGroup
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new MyChatServerInitializer());
try {
ChannelFuture future = serverBootstrap.bind(23333).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* Description: Netty 聊天服务端的初始化器
*
* Date: 2019/12/16 2:23
*
* @author ALion
*/
public class MyChatServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()))
.addLast(new StringDecoder(CharsetUtil.UTF_8))
.addLast(new StringEncoder(CharsetUtil.UTF_8))
.addLast(new MyChatServerHandler());
}
}
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
* Description: Netty 聊天服务器的处理器
*
* Date: 2019/12/16 2:30
*
* @author ALion
*/
public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
public static final String SEPARATOR = System.lineSeparator();
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyChatServerHandler.handlerAdded");
Channel channel = ctx.channel();
channelGroup.add(channel);
channelGroup.writeAndFlush("Server> " + channel.remoteAddress() + " add" + SEPARATOR);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyChatServerHandler.channelActive");
System.out.println(ctx.channel().remoteAddress() + " 连接");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel channel = ctx.channel();
System.out.println("===========|" + channel.remoteAddress() + "> " + msg);
for (Channel ch : channelGroup) {
if (ch != channel) {
ch.writeAndFlush(channel.remoteAddress() + "> " + msg + SEPARATOR);
} else {
ch.writeAndFlush("自己" + "> " + msg + SEPARATOR);
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyChatServerHandler.channelInactive");
System.out.println(ctx.channel().remoteAddress() + " 断开");
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyChatServerHandler.handlerRemoved");
Channel channel = ctx.channel();
channelGroup.remove(channel); // Netty会自动寻找断掉的channel,然后移除,可以不用手动移除
channelGroup.writeAndFlush("Server> " + channel.remoteAddress() + " remove" + SEPARATOR);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.Scanner;
/**
* Description: Netty 聊天客户端示例
*
* Date: 2019/12/16 2:41
*
* @author ALion
*/
public class MyChatClient {
public static void main(String[] args) {
// linux 下建议使用 EpollEventLoopGroup
EventLoopGroup loopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap()
.group(loopGroup)
.channel(NioSocketChannel.class)
.handler(new MyChatClientInitializer());
try {
ChannelFuture future = bootstrap.connect("127.0.0.1", 23333).sync();
Channel channel = future.channel();
Scanner scanner = new Scanner(System.in);
while (true) {
String msg = scanner.nextLine();
if ("exit".equals(msg)) break;
channel.writeAndFlush(msg + System.lineSeparator());
}
channel.close();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
loopGroup.shutdownGracefully();
}
}
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* Description: Netty 客户端的初始化器
*
* Date: 2019/12/16 2:44
*
* @author ALion
*/
public class MyChatClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()))
.addLast(new StringDecoder(CharsetUtil.UTF_8))
.addLast(new StringEncoder(CharsetUtil.UTF_8))
.addLast(new MyChatClientHandler());
}
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* Description: Netty 客户端的处理器
*
* Date: 2019/12/16 2:46
*
* @author ALion
*/
public class MyChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("MyClientHandler.channelActive");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// Channel channel = ctx.channel();
System.out.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}