下面我详细讲解一下“Netty网络编程实战之搭建Netty服务器”的完整攻略。
一、准备工作
1. 确认JDK版本是否为1.8及以上
2. 下载Netty 4.1以上版本的jar包
3. 安装Maven
二、创建项目
1.使用Maven创建项目
mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-quickstart -Dinteracti veMode=false
2.在pom.xml文件中添加Netty的依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
三、编写代码
1.创建Server类
public class Server {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(8080).sync();
System.out.println("Server started.");
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
2.创建ServerHandler类
public class ServerHandler extends SimpleChannelInboundHandler<String> {
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("Server received: " + msg);
ctx.writeAndFlush("Hello, client.");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
四、运行程序
1.运行Server类,控制台显示“Server started.”
2.使用telnet连接服务端,在命令行输入以下命令:
telnet localhost 8080
3.在命令行输入字符串,回车后即可看到“Hello, client.”的回复。
五、示例说明
1.客户端发送多行信息,服务端只回复单行信息。
修改ServerHandler类
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
try {
String request = in.toString(CharsetUtil.UTF_8);
System.out.println(request);
ctx.write(Unpooled.copiedBuffer("Hello, client.", CharsetUtil.UTF_8));
ctx.flush();
} finally {
ReferenceCountUtil.release(msg);
}
}
}
2.服务端返回时间信息,
修改ServerHandler类
public class ServerHandler extends SimpleChannelInboundHandler<String> {
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("Server received: " + msg);
ctx.writeAndFlush( LocalTime.now() + " : " + msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
以上就是 “Netty网络编程实战之搭建Netty服务器”的完整攻略,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Netty网络编程实战之搭建Netty服务器 - Python技术站