上节我们介绍了开发netty项目所必需的开发环境及工具的使用,这节我们来写第一个netty项目
开发步骤
第一步:打开https://search.maven.org 找到netty依赖库
第二步:打开上节创建的项目,修改build.gradle文件如下图:
第三步:新建类com.ssy.netty.MyServer.class
package com.ssy.netty; 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; /**
* netty作为长连接的服务器基于websoket,实现客户端与服务器端长连接。
*/
public class MyServer {
public static void main(String[] args) {
//负责接收客户端连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//处理连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup) // 绑定线程池
.channel(NioServerSocketChannel.class)
.childHandler(new ServerInitializer()); //绑定端口号
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
第四步:新建ServerInitializer类
package com.ssy.netty; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec; /**
* 绑定客户端连接时候触发操作
*/
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//负载http 请求编码解码
pipeline.addLast("httpServerCodec",new HttpServerCodec());
//实际处理请求
pipeline.addLast("httpServerHandler",new HttpServerHandler());
}
}
第五步:
package com.ssy.netty; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil; /**
* 给客户端返回字符串信息"hello world"
*/
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
/**
* 该方法用于接收从客户端接收的信息
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if(msg instanceof HttpRequest){
//设置返回内容,ByteBuf是一个引用计数对象实现ReferenceCounted,他就是在有对象引用的时候计数+1,无的时候计数-1,当为0对象释放内存
ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
//创建响应
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes()); ctx.writeAndFlush(response);
} }
}
第六步:启动MyServer服务端,命令行执行如下语句:
服务端返回:hello world
netty服务端程序到此介绍完毕,下节我们一起来写客户端程序。小伙伴们,让我们拭目以待吧!