red5(二) 防止盗链

Red5 防止盗链可通过调用客户端方法得到主机URI,判断是否在允许范围内,如果不是则断开连接。

具体实现是:Application 必须实现IPendingServiceCallback 接口,通过如下方法调用客户端方法

public boolean appConnect(IConnection conn, Object[] params)
  {
    if (conn instanceof IServiceCapableConnection) {
    	//调用客户端代码
    	IServiceCapableConnection sc = (IServiceCapableConnection) conn;
    	sc.invoke("clientMethod", new Object[]{"One", 1},this);
    }
    return super.appConnect(conn, params);
  }

 其中的clientMethod是客户端方法名称,new Object[]{"One", 1}是任意参数,this为必选

并书写接收客户端返回参数的方法

public void resultReceived(IPendingServiceCall arg0) {
  String host = arg0.getResult().toString();
  String allowHost = “http://localhost:28080/redxserver”;
  boolean allow = false;
  if(host.indexOf( allowHost)>0){
		 allow = true; 
  }
  if(!allow ){
		//获取当前的链接
		IConnection current = Red5.getConnectionLocal();
		current.close();
		 System.out.println("关闭连接");
  }else {
			 System.out.println("不关闭连接");
  }
}

 在播放器as内书写方法

var client1:Object=new Object();
client1.clientMethod=this.clientMethod;
_connection.client =client1;

 

private function clientMethod(str:String,num:Number):String{ 
    var str:String = ExternalInterface.call("window.top.location.href");
   return str;
}

还要修改BaseRTMPHandler.java中的方法,防止as方法出错了,仍然可以播放。

具体如下 

protected void handlePendingCallResult(RTMPConnection conn, Notify invoke) {
		final IServiceCall call = invoke.getCall();
		final IPendingServiceCall pendingCall = conn.retrievePendingCall(invoke.getInvokeId());
		if (pendingCall != null) {
			// The client sent a response to a previously made call.
			Object[] args = call.getArguments();
			if ((args != null) && (args.length > 0)) {
				// TODO: can a client return multiple results?
				pendingCall.setResult(args[0]);
			}
			Set callbacks = pendingCall.getCallbacks();
			if (!callbacks.isEmpty()) {
				HashSet tmp = new HashSet();
				tmp.addAll(callbacks);
				for (IPendingServiceCallback callback : tmp) {
					try {
						callback.resultReceived(pendingCall);
					} catch (Exception e) {

						log.error("Error while executing callback {} {}", callback, e);
						//关闭连接,添加下面两行即可	
						conn.close();
						break;
					}
				}
			}
		}
	}

 

 

通过以上方法即可实现防止盗链

已经优化了,请看下一篇文章 red5(三) 防止盗链

 

你可能感兴趣的:(视频服务器相关,视频)