直接上代码“”
server类
package com.montnets.customer.httpServer;
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;
public class server {
private static final int port = 6789; //设置服务端端口
private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接
private static ServerBootstrap sbt = new ServerBootstrap();
public static void main(String[] args) throws InterruptedException {
try {
sbt.group(eventLoopGroup, eventLoopGroup1);
sbt.channel(NioServerSocketChannel.class);
sbt.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast("encoder", new HttpResponseEncoder());
socketChannel.pipeline().addLast("decoder", new HttpRequestDecoder());
socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
socketChannel.pipeline().addLast(new NettyServerHandler());
}
});
// 服务器绑定端口监听
ChannelFuture f = sbt.bind(port).sync();
logger.info("企业微信消息推送接口线程启动成功");
// 监听服务器关闭监听
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程
}
}
}
NettyServerHandler类
package com.montnets.customer.httpserver;
import com.montnets.customer.interfaces.ICqrbOpration;
import com.montnets.customer.model.CqrbBeanconfig;
import com.montnets.log.MontnetsLog;
import com.montnets.model.BeanFactory;
import com.montnets.model.Config;
import io.netty.buffer.ByteBuf;
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;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private String result = "";
String reqPath = "aa";
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof FullHttpRequest)) {
result = "未知请求!";
send(ctx, result, HttpResponseStatus.BAD_REQUEST);
return;
}
FullHttpRequest httpRequest = (FullHttpRequest) msg;
try {
//获取路径
String path = httpRequest.getUri();
//获取参数
String body = getBody(httpRequest);
//获取请求方法
HttpMethod method = httpRequest.getMethod();
//如果不是这个路径,就直接返回错误
if (!reqPath.equalsIgnoreCase(path)) {
result = "请求路径错误!";
send(ctx, result, HttpResponseStatus.BAD_REQUEST);
return;
}
//如果是GET请求
if (HttpMethod.GET.equals(method)) {
result = "请求类型错误";
send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
return;
}
//如果是POST请求
if (HttpMethod.POST.equals(method)) {
//接受到的消息,做业务逻辑处理...
result = parsingAndDeal(body);
send(ctx, result, HttpResponseStatus.OK);
return;
}
//如果是PUT请求
if (HttpMethod.PUT.equals(method)) {
result = "请求类型错误";
send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
return;
}
//如果是DELETE请求
if (HttpMethod.DELETE.equals(method)) {
result = "请求类型错误";
send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
return;
}
} catch (Exception e) {
LOGGER.error("处理请求异常"+e);
} finally {
//释放请求
httpRequest.release();
}
}
/**
* 获取body参数
*
* @param request
* @return
*/
private String getBody(FullHttpRequest request) {
ByteBuf buf = request.content();
String bufString = buf.toString(CharsetUtil.UTF_8);
String decode = null;
try {
decode = URLDecoder.decode(bufString, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return decode;
}
/**
* 发送的返回值
*
* @param ctx 返回
* @param context 消息
* @param status 状态
*/
private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
response.headers().set("Content-Type", "text/plain; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
到这里服务端的大致框架已经搭建好,具体要做的业务可以在加上
简单的可以执行的demo例子可以查看一下博客: