-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNSHttpHandler.java
More file actions
238 lines (222 loc) · 8.53 KB
/
Copy pathNSHttpHandler.java
File metadata and controls
238 lines (222 loc) · 8.53 KB
1
package com.nullspace.http;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.handler.codec.http.DefaultFullHttpResponse;import io.netty.handler.codec.http.FullHttpRequest;import io.netty.handler.codec.http.FullHttpResponse;import io.netty.handler.codec.http.HttpHeaderNames;import io.netty.handler.codec.http.HttpMethod;import io.netty.handler.codec.http.HttpResponseStatus;import io.netty.handler.codec.http.HttpVersion;import io.netty.handler.codec.http.multipart.Attribute;import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;import io.netty.handler.codec.http.multipart.InterfaceHttpData;import io.netty.util.CharsetUtil;import java.io.File;import java.net.InetAddress;import java.nio.file.Files;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.List;import javax.activation.MimetypesFileTypeMap;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.nullspace.logic.NSSessionManager;import com.nullspace.packet.NSMessage;import com.nullspace.packet.NSMessageType;import com.nullspace.socket.NSSocketSession;public class NSHttpHandler extends ChannelInboundHandlerAdapter { public class HttpFutureResult implements ChannelFutureListener { ChannelHandlerContext mCtx; String mContext; HttpResponseStatus mStatus; public HttpFutureResult(ChannelHandlerContext ctx, String context, HttpResponseStatus status) { mCtx = ctx; mContext = context; mStatus = status; } @Override public void operationComplete(ChannelFuture future) throws Exception { send(mCtx, mContext, mStatus); } } private static Logger mLogger = LoggerFactory.getLogger("MJHttpHandler"); /* * http post * 1 sdk 调用 * */ private static String SessionID = "sid"; private static String OperatorID = "oid"; /* * 收到消息时,返回信息 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { send(ctx, "未知请求", HttpResponseStatus.BAD_REQUEST); return; } FullHttpRequest httpRequest = (FullHttpRequest)msg; try { HttpMethod method = httpRequest.method(); // 获取请求方法 //如果不是这个路径,就直接返回错误// if (!path.contains("/jiaoyou/advertisement"))// {// send(ctx, "非法请求!", HttpResponseStatus.BAD_REQUEST);// return;// } //如果是GET请求 if (HttpMethod.GET.equals(method)) { String path = httpRequest.uri(); // 获取路径 String body = getBody(httpRequest); // 获取参数 String userAgent = httpRequest.headers().get(HttpHeaderNames.USER_AGENT); String filePathString = NSHttpServer.ResourceDir().concat(path); File file = new File(filePathString); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String date = df.format(new Date()); if (!file.exists()) { send(ctx, path, HttpResponseStatus.NOT_FOUND); mLogger.error("{} {} {} Not Found", date, userAgent, path); } else { sendFileToClient(ctx, file, path); mLogger.info("{} {} {} OK", date, userAgent, path); } return; } //如果是POST请求 if (HttpMethod.POST.equals(method)) { // 是POST请求 HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(httpRequest); decoder.offer(httpRequest); List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas(); HashMap<String, String> map = new HashMap<>(); for (InterfaceHttpData parm : parmList) { Attribute data = (Attribute) parm; map.put(data.getName(), data.getValue()); } if (map.containsKey(SessionID) && map.containsKey(OperatorID)) { try { int sid = Integer.parseInt(map.get(SessionID).trim()); int oid = Integer.parseInt(map.get(OperatorID).trim()); NSSocketSession session = NSSessionManager.manager.GetSession(sid); if (session != null) { NSMessage mg = new NSMessage(); mg.mHead.mType = NSMessageType.GM; mg.mHead.mAddition = oid; mg.mHead.mSession = sid; try { session.WriteMessage(mg, new HttpFutureResult(ctx, "成功", HttpResponseStatus.OK)); } catch (Exception e) { send(ctx, "发送失败", HttpResponseStatus.NOT_FOUND); } } else { send(ctx, "会话不存在", HttpResponseStatus.BAD_REQUEST); } } catch (Exception e) { send(ctx, "参数解析出错", HttpResponseStatus.BAD_REQUEST); } } else { send(ctx, "缺少必要的参数", HttpResponseStatus.BAD_REQUEST); } return; } //如果是PUT请求 if (HttpMethod.PUT.equals(method)) { //接受到的消息,做业务逻辑处理... send(ctx, "PUT请求", HttpResponseStatus.OK); return; } //如果是DELETE请求 if (HttpMethod.DELETE.equals(method)) { //接受到的消息,做业务逻辑处理... send(ctx, "DELETE请求", HttpResponseStatus.OK); return; } } catch(Exception e) { System.out.println("处理请求失败!"); e.printStackTrace(); } finally { //释放请求 httpRequest.release(); } } /** * 获取body参数 * @param request * @return */ private String getBody(FullHttpRequest request) { ByteBuf buf = request.content(); return buf.toString(CharsetUtil.UTF_8); } public static String ResultCode(String context, HttpResponseStatus status) { return String.format("{\"resultCode\":\"%s\",\"message\":%d}", context, status.code()); } /** * 发送的返回值 * @param ctx 返回 * @param context 消息 * @param status 状态 */ private static void send(ChannelHandlerContext ctx, String context,HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(ResultCode(context, status), CharsetUtil.UTF_8)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private static void sendFileToClient(ChannelHandlerContext ctx, File file, String uri) throws Exception { ByteBuf buffer = Unpooled.copiedBuffer(Files.readAllBytes(file.toPath())); FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer); MimetypesFileTypeMap mimeTypeMap = new MimetypesFileTypeMap(); resp.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypeMap.getContentType(file)); ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE); } /* * 建立连接时,返回消息 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush("客户端" + InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! "); super.channelActive(ctx); }}