2016-10-12 58 views
1

我正在尝试使用Netty编写RTSP服务器。使用Netty发送http响应

现在的客户端发送请求

OPTIONS rtsp://localhost:8080 RTSP/1.0 
CSeq: 2 
User-Agent: LibVLC/2.2.4 (LIVE555 Streaming Media v2016.02.22) 

而且我想给下面的响应返回

RTSP/1.0 200 OK 
CSeq: 2 
Public: DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE 

我应该用什么来构造HTTP响应。我应该使用HttpResponse还是只使用普通字节数组并将其转换为ByteBuf?

我使用的Netty的版本是提前4.1.5

感谢。

回答

1

OPTIONS请求的RTSP响应只包含标题。

然后,你可以简单地创建作出反应并用填充:

FullHttpResponse response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); 
response.headers().add(RtspHeadersNames.PUBLIC, "DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); 
response.headers().add(RtspHeadersNames.CSEQ, cseq); 

的简化实现RTSP服务器应答期权的要求可能是:

import io.netty.bootstrap.ServerBootstrap; 
import io.netty.channel.*; 
import io.netty.channel.nio.NioEventLoopGroup; 
import io.netty.channel.socket.nio.NioServerSocketChannel; 
import io.netty.channel.socket.SocketChannel;  
import io.netty.handler.codec.http.*; 
import io.netty.handler.codec.rtsp.*; 

public class RtspServer { 
    public static class RtspServerHandler extends ChannelInboundHandlerAdapter { 
     @Override 
     public void channelReadComplete(ChannelHandlerContext ctx) { 
      ctx.flush(); 
     } 

     @Override 
     public void channelRead(ChannelHandlerContext ctx, Object msg) {      
      if (msg instanceof DefaultHttpRequest) {     
       DefaultHttpRequest req = (DefaultHttpRequest) msg; 
       FullHttpResponse response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); 
       response.headers().add(RtspHeadersNames.PUBLIC, "DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); 
       response.headers().add(RtspHeadersNames.CSEQ, req.headers().get("CSEQ")); 
       response.headers().set(RtspHeadersNames.CONNECTION, RtspHeadersValues.KEEP_ALIVE); 
       ctx.write(response); 
      } 
     } 
    } 

    public static void main(String[] args) throws Exception {  
     EventLoopGroup bossGroup = new NioEventLoopGroup(); 
     EventLoopGroup workerGroup = new NioEventLoopGroup(); 
     try { 
      ServerBootstrap b = new ServerBootstrap(); 
      b.group(bossGroup, workerGroup); 
      b.channel(NioServerSocketChannel.class);    
      b.childHandler(new ChannelInitializer<SocketChannel>() { 
       @Override 
       public void initChannel(SocketChannel ch) { 
        ChannelPipeline p = ch.pipeline(); 
        p.addLast(new RtspDecoder(), new RtspEncoder()); 
        p.addLast(new RtspServerHandler()); 
       } 
      }); 

      Channel ch = b.bind(8554).sync().channel(); 
      System.err.println("Connect to rtsp://127.0.0.1:8554"); 
      ch.closeFuture().sync(); 
     } finally { 
      bossGroup.shutdownGracefully(); 
      workerGroup.shutdownGracefully(); 
     }  
    } 
} 
0

你想使用FullHttpResponse与管道中的RTSP处理程序。