demo
Posted smallwolf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了demo相关的知识,希望对你有一定的参考价值。
使用Idea加Gradle构建一个Netty项目
New Project -> Gradle -> Next
build.gradle 相当于maven的pom文件 可以去maven中央仓库寻找依赖
group 'com.shengsiyuan'
version '1.0-SNAPSHOT'
apply plugin: 'java'
//配置JDK的版本号
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories
maven
//配置阿里云的仓库下载速度飞快
url "https://maven.aliyun.com/nexus/content/groups/public"
mavenCentral()
dependencies
//将拷贝的依赖复制到这里是不是比maven简洁
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'io.netty', name: 'netty-all', version: '4.1.39.Final'
编写代码
public class TestServer
public static void main(String[] args) throws InterruptedException
//定义两个事件组
//接收连接但是不对连接做任何处理会把事情交给workerGroup去做
EventLoopGroup bossGroup = new NioEventLoopGroup();
//真正处理连接的
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
//启动服务
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioserverSocketChannel.class)
.childHandler(new TestServerInitializer());
//绑定端口
ChannelFuture sync = serverBootstrap.bind(8899).sync();
sync.channel().closeFuture().sync();
finally
//优雅的关闭Netty
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
public class TestServerInitializer extends ChannelInitializer<SocketChannel>
/**
* 连接一旦被创建就会调用这个方法,添加自定义的处理器
* @param ch
* @throws Exception
*/
@Override
protected void initChannel(SocketChannel ch) throws Exception
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServerCodec",new HttpServerCodec());
pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject>
/**
* 读取客户端所发出的请求,并响应到客户端的方法
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception
if (msg instanceof HttpRequest)
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);
请求 http://localhost:8899 响应Hello World!
以上是关于demo的主要内容,如果未能解决你的问题,请参考以下文章