Netty可以通过一些handler实现简单的http服务器。具体有三个类,分别是HttpServer.java、ServerHandlerInit.java、BusiHandler.java。

具体代码如下:

HttpServer.java

package cn.enjoyedu.server;

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;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class HttpServer {
public static final int port = 6789; //设置服务端端口
private static EventLoopGroup group = new NioEventLoopGroup();
private static ServerBootstrap b = new ServerBootstrap();
private static final boolean SSL = true; public static void main(String[] args) throws Exception {
final SslContext sslCtx;
if (SSL) {
//netty为我们提供的ssl加密,缺省
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(),
ssc.privateKey()).build();
} else {
sslCtx = null;
}
try {
b.group(group);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ServerHandlerInit(sslCtx));
// 服务器绑定端口监听
ChannelFuture f = b.bind(port).sync();
System.out.println("服务端启动成功,端口是:"+port);
// 监听服务器关闭监听
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}

ServerHandlerInit.java

package cn.enjoyedu.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class ServerHandlerInit extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public ServerHandlerInit(SslContext sslCtx) {
this.sslCtx = sslCtx;
} @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline ph = ch.pipeline();
if (sslCtx != null) {
ph.addLast(sslCtx.newHandler(ch.alloc()));
}
//http响应编码
ph.addLast("encode",new HttpResponseEncoder());
//http请求编码
ph.addLast("decode",new HttpRequestDecoder());
//聚合http请求
ph.addLast("aggre",
new HttpObjectAggregator(10*1024*1024));
//启用http压缩
ph.addLast("compressor",new HttpContentCompressor());
//自己的业务处理
ph.addLast("busi",new BusiHandler()); }
}

BusiHandler.java

package cn.enjoyedu.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class BusiHandler extends ChannelInboundHandlerAdapter {
private String result=""; private void send(String content, ChannelHandlerContext ctx,
HttpResponseStatus status){
FullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
Unpooled.copiedBuffer(content,CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE,
"text/plain;charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } /*
* 收到消息时,返回信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
String result="";
//接收到完成的http请求
FullHttpRequest httpRequest = (FullHttpRequest)msg; try{
String path = httpRequest.uri();
String body = httpRequest.content().toString(CharsetUtil.UTF_8);
HttpMethod method = httpRequest.method();
if(!"/test".equalsIgnoreCase(path)){
result = "非法请求:"+path;
send(result,ctx,HttpResponseStatus.BAD_REQUEST);
return;
} //处理http GET请求
if(HttpMethod.GET.equals(method)){
System.out.println("body:"+body);
result="Get request,Response="+RespConstant.getNews();
send(result,ctx,HttpResponseStatus.OK);
} //处理http POST请求
if(HttpMethod.POST.equals(method)){
//..... } }catch(Exception e){
System.out.println("处理请求失败!");
e.printStackTrace();
}finally{
httpRequest.release();
}
} /*
* 建立连接时,返回消息
*/
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
System.out.println("连接的客户端地址:"
+ ctx.channel().remoteAddress());
}
}

说明:

HttpServer.java就是实现一个http服务器,然后具体的handler入栈则是通过ServerHandlerInit.java实现。同时具体的http逻辑处理则是BusiHandler.java。

该示例实现了https的实现。

Netty实现简易http_server的更多相关文章

  1. Netty(四)基于Netty 的简易版RPC

    3.1 RPC 概述 下面的这张图,大概很多小伙伴都见到过,这是 Dubbo 官网中的一张图描述了项目架构的演进过程 它描述了每一种架构需要的具体配置和组织形态.当网站流量很小时,只需一个应用,将所有 ...

  2. Netty(三)基于Bio和Netty 的简易版Tomcat

    参考代码: https://github.com/FLGBetter/tomcat-rpc-demo

  3. Netty核心组件介绍及手写简易版Tomcat

    Netty是什么: 异步事件驱动框架,用于快速开发高i性能服务端和客户端 封装了JDK底层BIO和NIO模型,提供高度可用的API 自带编码解码器解决拆包粘包问题,用户只用关心业务逻辑 精心设计的Re ...

  4. 使用Netty实现HTTP服务器

    使用Netty实现HTTP服务器,使用Netty实现httpserver,Netty Http Netty是一个异步事件驱动的网络应用程序框架用于快速开发可维护的高性能协议服务器和客户端.Netty经 ...

  5. 2、Netty基础

    一.前言 主要包含下面内容: 初识 Netty: 使用 Java NIO 搭建简单的客户端与服务端实现网络通讯: 使用 Netty 搭建简单的客户端与服务端实现网络通讯: Netty 底层操作与 Ja ...

  6. 阿里的Netty知识点你又了解多少

    前言 Netty 是一个可以快速开发网络应用程序的 NIO 框架,它大大简化了 TCP 或者 UDP 服务器的网络编程.Netty 的简易和快速开发并不意味着由它开发的程序将失去可维护性或者存在性能问 ...

  7. 实现分布式服务注册及简易的netty聊天

    现在很多地方都会用到zookeeper, 用到它的地方就是为了实现分布式.用到的场景就是服务注册,比如一个集群服务器,需要知道哪些服务器在线,哪些服务器不在线. ZK有一个功能,就是创建临时节点,当机 ...

  8. 基于Netty的RPC简易实现

    代码地址如下:http://www.demodashi.com/demo/13448.html 可以给你提供思路 也可以让你学到Netty相关的知识 当然,这只是一种实现方式 需求 看下图,其实这个项 ...

  9. 一个简易的netty udp服务端

    netty号称java高性能网络库,为人帮忙中,研究了下,写了一个demo.反复调试,更改,局域网两个客户端同时for循环发10000个20字节的数据包,入库mysql,居然没丢. 思路,netty的 ...

随机推荐

  1. ql常见面试题 受用了

    //转至:http://www.cnblogs.com/GT_Andy/archive/2009/12/25/1921911.html 1. 用一条SQL 语句 查询出每门课都大于80 分的学生姓名 ...

  2. Linux普通用户不能使用TAB键、上下键

    出发点 今天安装使用kail linux的时候发现tab键命令不能补全, 结合ubuntu, 因默认ubuntu创建的普通帐号,默认shell为/bin/sh,而这不支持tab等键的,所以将「指定用户 ...

  3. ldap服务备份与恢复

    备份: cat ldap_backup.sh #!/bin/bash/usr/sbin/slapcat >/S3/openldap/openldap_backup_`date -d " ...

  4. (13flask继续研究)自己动手,编写神经网络程序,解决Mnist问题,并网络化部署

    解决3个问题: 1.自己实现一例flask项目: 2.在flask中,如何调用json传值: 3.进一步读懂现有代码. Flask 在整个系统中是作为一个后台框架,对外提供 api 服务,因此对它的理 ...

  5. FJUT seventh的tired树上路径(01字典树)题解

    思路(来自题解): 众所周知树上两个点xy的距离是deep[x]+deep[y]-deep[lca(x,y)]*2 然后我们把这个加减法换成异或,我们就会发现,deep[lca(x,y)]被消掉了 所 ...

  6. 【第四十章】Spring Boot 自定义拦截器

    1.首先编写拦截器代码 package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import ja ...

  7. Android开发——去掉系统自带标题栏的几种方式

    https://blog.csdn.net/qq_28585471/article/details/75991613 今天在练习自定义标题栏(Android初级开发(四)——补充3)的过程中遇到了隐藏 ...

  8. it做形式主语的句子

    1. it was considerate of you to visit my mother every day and (to) bring me your notes to help me wi ...

  9. Docker 开发概述

    This page lists resources for application developers using Docker. Develop new apps on Docker If you ...

  10. zepto 入门

    2017-03-17 文章来源:http://www.cnblogs.com/daysme zepto 简介 jq虽然有一些衍生的插件可用在移动端上,但它有点大. click 有,但有问题 onmou ...