netty 处理 get 请求

请求样式:

http://10.32.7.7:2360/?name=aaa   注意这里必须是问号,name  等号的形式

代码留存

package com.cip.arch.enne;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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.stream.ChunkedWriteHandler;

public class NettyServer
{
	private static final int SERVER_PORT = 2360;
	private static final String DEFAULT_URL = "/";
	
	public void start(final String ip) throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try
		{
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>()
					{
						@Override
						protected void initChannel(SocketChannel ch) throws Exception
						{
							ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
							ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
							ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
							ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
							ch.pipeline().addLast("HttpServerHandler", new NettyServerHandler());
						}
					});
			ChannelFuture future = b.bind(ip, SERVER_PORT).sync();
			System.out.println("HTTP server start: " + "http://"+ip+":" + SERVER_PORT + DEFAULT_URL);
			future.channel().closeFuture().sync();
		}
		finally
		{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		String ip = "10.32.7.7";
		new NettyServer().start(ip);
	}
}


package com.ctp.sech.engi;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
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.QueryStringDecoder;

public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
	
	StringBuilder sb = new StringBuilder();
	JSONArray jsonarray = new JSONArray();
	
	public NettyServerHandler() {
		jsonarray.add(getJsonObj("name", "ar.sear.ocalplay"));
		jsonarray.add(getJsonObj("name", "ar.sear.ticket"));
		jsonarray.add(getJsonObj("name", "ar.sear.tel"));
		jsonarray.add(getJsonObj("name", "ar.sear.surehotel"));
	}
	
	public JSONObject getJsonObj(String name, String value) {
		JSONObject jsonobj = new JSONObject();
		jsonobj.put(name,value);
		return jsonobj;
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) //
			throws Exception {//函数执行次数?
		//解析get请求参数
		QueryStringDecoder decoder = new QueryStringDecoder(msg.getUri());  
		Map<String, List<String>> parame = decoder.parameters();  
		for(Entry<String, List<String>> entry : parame.entrySet()) {
			System.out.println(entry.getKey() + " : " +entry.getValue());
			
		}
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); // 响应
		response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
		ByteBuf responseContentByteBuf = Unpooled.copiedBuffer(JSON.toJSONString(jsonarray,SerializerFeature.DisableCircularReferenceDetect).getBytes(Charset.forName("utf-8")));
		response.headers().set("Access-Control-Allow-Origin","*"); // 跨域
		response.headers().set(CONTENT_LENGTH, responseContentByteBuf.readableBytes());
		response.content().writeBytes(responseContentByteBuf);
		responseContentByteBuf.release();//zuoyong?
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);//
	}
	
}


可以使用Netty处理在线播放mp4请求,下面是大致的实现思路: 1. 创建一个Netty服务器,监听指定的端口,等待客户端连接。 2. 当有客户端连接时,创建一个ChannelPipeline,添加一系列的ChannelHandler,用于处理请求和响应。 3. 当收到客户端的请求时,解析请求中的URL,获取要播放的mp4文件的路径。 4. 使用Java的NIO API读取mp4文件,将数据写入响应的Channel中,实现流式传输。 5. 客户端收到响应后,使用HTML5的video标签播放mp4文件,实现在线播放。 示例代码如下: ```java public class Mp4StreamingServer { private final int port; public Mp4StreamingServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new Mp4StreamingServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = Integer.parseInt(args[0]); new Mp4StreamingServer(port).run(); } } ``` ```java public class Mp4StreamingServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_LENGTH = "Content-Length"; private static final String KEEP_ALIVE = "keep-alive"; @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (request.method() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } String uri = request.uri(); String path = sanitizeUri(uri); if (path == null) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } File file = new File(path); if (!file.exists() || file.isHidden() || !file.isFile()) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } if (!file.canRead()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } RandomAccessFile raf = new RandomAccessFile(file, "r"); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { if (total < 0) { System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*"); private String sanitizeUri(String uri) { try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { try { uri = URLDecoder.decode(uri, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new Error(); } } if (!uri.startsWith("/")) { return null; } uri = uri.replace('/', File.separatorChar); if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) { return null; } return System.getProperty("user.dir") + File.separator + uri; } private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private static void setContentTypeHeader(HttpResponse response, File file) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath())); } } ``` 在上面的示例代码中,Mp4StreamingServer类是启动Netty服务器的入口,它创建了一个ServerBootstrap实例,配置了NioEventLoopGroup、NioServerSocketChannel、ChannelInitializer和Mp4StreamingServerHandler等组件,并监听指定的端口,等待客户端连接。 Mp4StreamingServerHandler类是处理请求和响应的核心,它继承了SimpleChannelInboundHandler<FullHttpRequest>,重写了channelRead0方法,用于读取客户端的请求,解析请求中的URL,获取要播放的mp4文件的路径,读取mp4文件并将数据写入响应的Channel中,实现流式传输。同时,如果客户端请求中包含keep-alive头,则在响应中添加该头,以保持连接,避免浪费资源。最后,通过调用ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)方法,通知客户端数据传输完成,释放资源。 总之,使用Netty处理在线播放mp4请求,可以提高服务器的并处理能力和吞吐量,同时实现实时流媒体传输,提升用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值