• How to set up protocol rollover with ActionScript

    Here is a quick snippet of ActionScript 2 code that illustrates how to attempt connections over multiple RTMP protocols (RTMP and RTMPT). It will first try RTMP over port 443. If that fails, it will attempt RTMPT over port 443. This is just a simple example and can easily be expanded to cover other protcol rollover needs.

    To enable port 443 in the Wowza media server, edit [install-dir]/conf/VHost.xml /HostPort /Port "1935" and change to "1935,443".
    <Port>1935,443</Port>
    Remember to turn off any web servers that might be using port 443.

    var nc:NetConnection = new NetConnection()
    var ncConnectTimer:Number = 0;
    var ncConnectTimeout:Number = 3000; // 3 seconds
    var ncDomain:String = "localhost";
    var ncPort:Number = 443;
    var ncApplication:String = "fastplay";
    var ncTryIndex:Number = 0;
    
    function init()
    {
    	nc.onStatus = function(infoObj:Object)
    	{
    		trace("nc.onStatus: "+infoObj.code);
    		if (infoObj.code == "NetConnection.Connect.Success")
    			clearConnectTimer();
    		else if (infoObj.code == "NetConnection.Connect.Failed")
    			tryReconnect();
    	}
    }
    
    function clearConnectTimer()
    {
    	if (ncConnectTimer != 0)
    		clearInterval(ncConnectTimer);
    	ncConnectTimer = 0;
    }
    
    function tryConnect()
    {
    	clearConnectTimer();
    	
    	var url:String = "";
    	switch(ncTryIndex)
    	{
    		case 0:
    			url = "rtmp://"+ncDomain+":"+ncPort+"/"+ncApplication;
    			break;
    		case 1:
    			url = "rtmpt://"+ncDomain+":"+ncPort+"/"+ncApplication;
    			break;
    		default:
    			trace("Failed to connect after "+ncTryIndex+" tries");
    			break;
    	}
    	
    	if (url.length > 0)
    	{
    		nc.connect(url);
    		ncConnectTimer = setInterval(_root, "tryReconnect", ncConnectTimeout);
    	}
    }
    
    function tryReconnect()
    {
    	trace("tryReconnect");
    	clearConnectTimer();
    	ncTryIndex++;
    	tryConnect();
    }
    
    init();
    tryConnect();
    Note: Port 443 is the default port used for SSL based HTTP traffic. We are using this port since it is likely open on most corporate firewalls and all stateful packet inspection that might block RTMPT based traffic should be turned off.

    Note: There is also an interesting solution available here:

    http://code.google.com/p/netconnectionsmart/

    If you're having problems or want to discuss this article, post in our forum.