Netty 是一款强大的异步事件驱动网络应用框架,广泛应用于高并发场景中。想快速上手 Netty 吗?本文将通过一个简单的入门实例带你了解其核心概念!🚀
首先,我们需要引入 Netty 的依赖库。在 Maven 项目中添加以下配置:
```xml
```
接下来,我们创建一个简单的服务器端代码。服务端监听端口并接收客户端消息:
```java
public class NettyServer {
public static void main(String[] args) throws Exception {
// 创建服务器启动器
new ServerBootstrap()
.group(new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("收到消息:" + msg);
}
});
}
})
.bind(8080).sync();
}
}
```
客户端则负责发送数据到服务器:
```java
public class NettyClient {
public static void main(String[] args) throws Exception {
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new StringEncoder());
}
});
ChannelFuture f = b.connect("localhost", 8080).sync();
f.channel().writeAndFlush("Hello Netty!");
f.channel().closeFuture().sync();
}
}
```
运行后,服务器会打印接收到的消息,表明通信成功!💡
通过这个小例子,你是否对 Netty 有了初步认识?快来动手实践吧!💪