flashのp2p

16 11 2010

月曜日と火曜日は合宿免許の電話がかかってくるので早く帰宅。

勉強の休憩がてらFlash10.1から導入されたNetGroupクラスを使って
p2pの動画配信できまいかと試行錯誤したんだけれども、できなかった。

http://paso.hopto.org/broad.swf
http://paso.hopto.org/receive.swf

ローカルで二つ立ち上げると見えるんだけれど、グローバルだとなぜかつながらにゃい。


Helpにあったサンプルをいじくりまわしながら。つづりはいくらかみすってます。

ブロードキャスター

package {
	import flash.net.*;
	import flash.events.*;
	import flash.display.*;
	import flash.media.*;
	import flash.utils.*;
	import spark.components.*;
	import flash.text.*;
		public class Main extends Sprite{
			private var netConnection:NetConnection = null;
            private var netStream:NetStream = null;
            private var netGroup:NetGroup = null;
            private var video:Video = null;
            private var sequenceNumber:uint = 0;
            private var resizeTimer:Timer = null;
			private var groupSpecifier:GroupSpecifier;
			private var videoDisplay:Video = new Video();//320*240
			private var textBox:TextField;

			//private var videoCount:uint = 1;

            private const SERVER:String = "rtmfp://stratus.adobe.com/";
            private const DEVKEY:String = "でぃべろっぱーID";

            private var connected:Boolean = false;
            private var joinedGroup:Boolean = false;

			public function Main():void
			{
				Standby();
				OnApplicationComplete();
			}
			public function Standby():void {

				//videoDisplay.y = 240;
				addChild(videoDisplay);
				textBox = new TextField();
				textBox.y = 240;
				textBox.width = 640;
				textBox.height = 300;
				//textBox.x = 320;
				addChild(textBox);

				}

            private function OnApplicationComplete():void
            {
                //userName.text = "user " + int(Math.random() * 65536);

                //groupName.text = "channel" + (int(Math.random() * 899) + 101);
				DoConnect();
                resizeTimer = new Timer(2000.0);
                resizeTimer.addEventListener(TimerEvent.TIMER, DoResizeVideo);
                resizeTimer.start();
            }

           /* private function textBox.appendText("\n"+msg:Object):void
            {
                statusLog.text += msg;
                statusLog.verticalScrollPosition = statusLog.textHeight;
                statusLog.validateNow();
            }*/

            private function NetStatusHandler(e:NetStatusEvent):void
            {
                textBox.appendText("\n"+e.info.code);
                switch(e.info.code)
                {
                case "NetConnection.Connect.Success":
				textBox.appendText("\n ID:" + netConnection.nearID);
                    OnConnect();
                    break;

                case "NetConnection.Connect.Closed":
                case "NetConnection.Connect.Failed":
                case "NetConnection.Connect.Rejected":
                case "NetConnection.Connect.AppShutdown":
                case "NetConnection.Connect.InvalidApp":
                    OnDisconnect();
                    break;

                case "NetStream.Connect.Success": // e.info.stream

                    break;

                case "NetStream.Connect.Rejected": // e.info.stream
                case "NetStream.Connect.Failed": // e.info.stream
                    DoDisconnect();
                    break;

                case "NetGroup.Connect.Success": // e.info.group
                    OnNetGroupConnect();
                    break;

                case "NetGroup.Connect.Rejected": // e.info.group
                case "NetGroup.Connect.Failed": // e.info.group
                    DoDisconnect();
                    break;

                case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID
                    OnPosting(e.info.message);
                    break;

                case "NetStream.MulticastStream.Reset":
                case "NetStream.Buffer.Full":
                    DoResizeVideo();
                    break;

                case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal
                case "NetGroup.LocalCoverage.Notify": //
                case "NetGroup.Neighbor.Connect": // e.info.neighbor
                case "NetGroup.Neighbor.Disconnect": // e.info.neighbor
                case "NetGroup.MulticastStream.PublishNotify": // e.info.name
					//OnReceive(e.info.name);
					break;
                case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name
					//textBox.appendText("\n"+e.info.name);
					break;
                case "NetGroup.Replication.Fetch.SendNotify": // e.info.index
                case "NetGroup.Replication.Fetch.Failed": // e.info.index
                case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object
                case "NetGroup.Replication.Request": // e.info.index, e.info.requestID
                default:
                    break;
                }
            }

            private function DoConnect():void
            {
                textBox.appendText("\n"+"Connecting to \"" + SERVER + "\" ...\n");
                netConnection = new NetConnection();
                netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
                netConnection.connect(SERVER + DEVKEY);
            }

            private function OnConnect():void
            {

                textBox.appendText("\n"+"Connected\n");
                connected = true;

                groupSpecifier = new GroupSpecifier("Live");
                groupSpecifier.multicastEnabled = true;
                groupSpecifier.postingEnabled = true;
                groupSpecifier.serverChannelEnabled = true;
				groupSpecifier.ipMulticastMemberUpdatesEnabled = true;
				groupSpecifier.addIPMulticastAddress("224.0.0.254:30000");

                netGroup = new NetGroup(netConnection, groupSpecifier.toString());
                netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);

                textBox.appendText("\n"+"Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n");
            }
			/*private function OnReceive(str:String):void {
				textBox.appendText("\n"+str);
				var recNetStream:NetStream = new NetStream(netConnection, groupSpecifier.toString());
				var receiveVideo:Video = new Video();
				receiveVideo.x = 320 * videoCount;
				videoCount++;
				addChild(receiveVideo);
				recNetStream.play(str);
				receiveVideo.attachNetStream(recNetStream);

				}*/
            private function OnNetStreamConnect():void
            {
                netStream.client = this;

                /*var mic:Microphone = Microphone.getMicrophone();
                if(mic)
                {
                    mic.codec = SoundCodec.SPEEX;
                    mic.setSilenceLevel(0);

                    netStream.attachAudio(mic);

                    textBox.appendText("\n"+"got microphone\n");
                }*/

                var camera:Camera = Camera.getCamera();
                if(camera)
                {
                    camera.setMode(320, 240, 10);
                    camera.setQuality(30000, 0);
                    camera.setKeyFrameInterval(15);

                    videoDisplay.attachCamera(camera);
                    //videoDisplay.maintainAspectRatio = true;

                    netStream.attachCamera(camera);

                    textBox.appendText("\n"+"got camera\n");
                }

                netStream.publish("stream");
            }

            private function OnNetGroupConnect():void
            {
                netStream = new NetStream(netConnection, groupSpecifier.toString());
                netStream.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
				OnNetStreamConnect();

                joinedGroup = true;
            }

            private function DoDisconnect():void
            {
                if(netConnection)
                    netConnection.close();
                videoDisplay.attachCamera(null);
            }

            private function OnDisconnect():void
            {
                textBox.appendText("\n"+"Disconnected\n");
                netConnection = null;
                netStream = null;
                netGroup = null;
                connected = false;
                joinedGroup = false;
            }

            private function ClearChatText():void
            {
                //chatText.text = "";
            }

            private function DoPost():void
            {
                /*var message:Object = new Object;

                message.user = userName.text;
                message.text = chatText.text;
                message.sequence = sequenceNumber++;
                message.sender = netConnection.nearID;

                netGroup.post(message);

                textBox.appendText("\n"+"==> " + chatText.text + "\n");

                chatText.callLater(ClearChatText);*/
            }

            private function OnPosting(message:Object):void
            {
                textBox.appendText("\n"+"<" + message.user + "> " + message.text + "\n");
            }

            private function DoResizeVideo(ignored:* = null):void
            {
                if(video)
                {
                    if( (0 == video.videoHeight)
                     || (0 == video.videoWidth)
                    )
                    {
                        video.height = videoDisplay.height;
                        video.width = videoDisplay.width;
                        video.x = 0;
                        video.y = 0;
                    }
                    else
                    {
                        var videoAspect:Number = Number(video.videoWidth) / Number(video.videoHeight);
                        var displayAspect:Number = Number(videoDisplay.width) / Number(videoDisplay.height);
                        var adjustFactor:Number;

                        if(videoAspect >= displayAspect) // video is wider than display
                        {
                            adjustFactor = Number(video.videoWidth) / Number(videoDisplay.width);
                            video.width = videoDisplay.width;
                            video.height = int(Number(video.videoHeight) / adjustFactor);
                            video.x = 0;
                            video.y = int((videoDisplay.height - video.height) / 2);
                        }
                        else
                        {
                            adjustFactor = Number(video.videoHeight) / Number(videoDisplay.height);
                            video.height = videoDisplay.height;
                            video.width = int(Number(video.videoWidth) / adjustFactor);
                            video.x = int((videoDisplay.width - video.width) / 2);
                            video.y = 0;
                        }
                    }
                }
            }

            public function onPlayStatus(info:Object):void {}
            public function onMetaData(info:Object):void {}
            public function onCuePoint(info:Object):void {}
            public function onTextData(info:Object):void {}

            public function ValidateConnectAllowed(isConnected:Boolean, groupNameText:String):Boolean
            {
                return (!isConnected) && (groupNameText.length > 0);
            }
	 }
 }

レシーバー

package {
	import flash.net.*;
	import flash.events.*;
	import flash.display.*;
	import flash.media.*;
	import flash.utils.*;
	import spark.components.*;
	import flash.text.*;
		public class Receive extends Sprite{
			private var netConnection:NetConnection = null;
            private var netStream:NetStream = null;
            private var netGroup:NetGroup = null;
            private var video:Video = null;
            private var sequenceNumber:uint = 0;
            private var resizeTimer:Timer = null;
			private var groupSpecifier:GroupSpecifier;
			private var videoDisplay:Video = new Video();//320*240
			private var textBox:TextField;
			private var textInput:TextField;
			
			//private var videoCount:uint = 1;

            private const SERVER:String = "rtmfp://stratus.adobe.com/";
            private const DEVKEY:String = "でぃべろっぱーID";

            private var connected:Boolean = false;
            private var joinedGroup:Boolean = false;

			public function Receive():void 
			{
				Standby();
				OnApplicationComplete();
			}
			public function Standby():void {
				
				//videoDisplay.y = 240;
				addChild(videoDisplay);
				
				textBox = new TextField();
				addChild(textBox);
				textBox.y = 260;
				textBox.width = 640;
				textBox.height = 300;
				textBox.border = true;
				//textBox.x = 320;
				
				//textBox.text = "test";
				textInput = new TextField();
				textInput.y = 240;
				textInput.width = 300;
				textInput.height = 20;
				textInput.border = true;
				textInput.type = TextFieldType.INPUT;
				//textBox.x = 320;
				addChild(textInput);
				
				textInput.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
				
				}
				private function pressKey(e:KeyboardEvent ):void {
					if (e.keyCode == 13) {
						netGroup.addNeighbor(textInput.text);
						//textInput.appendText("<p");
						}
					};
            private function OnApplicationComplete():void
            {
                //userName.text = "user " + int(Math.random() * 65536);

                //groupName.text = "channel" + (int(Math.random() * 899) + 101);
				DoConnect();
                resizeTimer = new Timer(2000.0);
                resizeTimer.addEventListener(TimerEvent.TIMER, DoResizeVideo);
                resizeTimer.start();
            }

           /* private function textBox.appendText("\n"+msg:Object):void
            {
                statusLog.text += msg;
                statusLog.verticalScrollPosition = statusLog.textHeight;
                statusLog.validateNow();
            }*/

            private function NetStatusHandler(e:NetStatusEvent):void
            {
                textBox.appendText("\n"+e.info.code);
                switch(e.info.code)
                {
                case "NetConnection.Connect.Success":
					textBox.appendText("\n ID:" + netConnection.nearID);
                    OnConnect();
                    break;

                case "NetConnection.Connect.Closed":
                case "NetConnection.Connect.Failed":
                case "NetConnection.Connect.Rejected":
                case "NetConnection.Connect.AppShutdown":
                case "NetConnection.Connect.InvalidApp":
                    OnDisconnect();
                    break;

                case "NetStream.Connect.Success": // e.info.stream
                    
                    break;

                case "NetStream.Connect.Rejected": // e.info.stream
                case "NetStream.Connect.Failed": // e.info.stream
                    DoDisconnect();
                    break;

                case "NetGroup.Connect.Success": // e.info.group
                    OnNetGroupConnect();
                    break;

                case "NetGroup.Connect.Rejected": // e.info.group
                case "NetGroup.Connect.Failed": // e.info.group
                    DoDisconnect();
                    break;

                case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID
                    OnPosting(e.info.message);
                    break;


                case "NetStream.MulticastStream.Reset":
                case "NetStream.Buffer.Full":
                    DoResizeVideo();
                    break;

                case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal
                case "NetGroup.LocalCoverage.Notify": //
                case "NetGroup.Neighbor.Connect": // e.info.neighbor
                case "NetGroup.Neighbor.Disconnect": // e.info.neighbor
                case "NetGroup.MulticastStream.PublishNotify": // e.info.name
					OnReceive(e.info.name as String);
					break;
                case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name
					textBox.appendText("\n"+e.info.name);
					break;
                case "NetGroup.Replication.Fetch.SendNotify": // e.info.index
                case "NetGroup.Replication.Fetch.Failed": // e.info.index
                case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object
                case "NetGroup.Replication.Request": // e.info.index, e.info.requestID
                default:
                    break;
                }
            }

            private function DoConnect():void
            {
                textBox.appendText("\n"+"Connecting to \"" + SERVER + "\" ...\n");
                netConnection = new NetConnection();
                netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
                netConnection.connect(SERVER + DEVKEY);
            }

            private function OnConnect():void
            {
                

                textBox.appendText("\n"+"Connected\n");
                connected = true;

                groupSpecifier = new GroupSpecifier("Live");
                groupSpecifier.multicastEnabled = true;
                groupSpecifier.postingEnabled = true;
                groupSpecifier.serverChannelEnabled = true;
				groupSpecifier.ipMulticastMemberUpdatesEnabled = true;
				groupSpecifier.addIPMulticastAddress("224.0.0.254:30000");



                netGroup = new NetGroup(netConnection, groupSpecifier.toString());
                netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);

                textBox.appendText("\n"+"Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n");
            }
			private function OnReceive(str:String):void {
				//textBox.appendText("\n"+str);

				
				}
            private function OnNetStreamConnect():void
            {
                netStream.client = this;

                /*var mic:Microphone = Microphone.getMicrophone();
                if(mic)
                {
                    mic.codec = SoundCodec.SPEEX;
                    mic.setSilenceLevel(0);

                    netStream.attachAudio(mic);

                    textBox.appendText("\n"+"got microphone\n");
                }*/

				//var recNetStream:NetStream = new NetStream(netConnection, groupSpecifier.toString());
				//var receiveVideo:Video = new Video();
				//addChild(receiveVideo);
				netStream.play("stream");
				videoDisplay.attachNetStream(netStream);
				
            }

            private function OnNetGroupConnect():void
            {
                netStream = new NetStream(netConnection, groupSpecifier.toString());
                netStream.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler);
				OnNetStreamConnect();
				
                joinedGroup = true;
            }

            private function DoDisconnect():void
            {
                if(netConnection)
                    netConnection.close();
                videoDisplay.attachCamera(null);
            }

            private function OnDisconnect():void
            {
                textBox.appendText("\n"+"Disconnected\n");
                netConnection = null;
                netStream = null;
                netGroup = null;
                connected = false;
                joinedGroup = false;
            }

            private function ClearChatText():void
            {
                //chatText.text = "";
            }

            private function DoPost():void
            {
                /*var message:Object = new Object;

                message.user = userName.text;
                message.text = chatText.text;
                message.sequence = sequenceNumber++;
                message.sender = netConnection.nearID;

                netGroup.post(message);

                textBox.appendText("\n"+"==> " + chatText.text + "\n");

                chatText.callLater(ClearChatText);*/
            }

            private function OnPosting(message:Object):void
            {
                textBox.appendText("\n"+"<" + message.user + "> " + message.text + "\n");
            }

            private function DoResizeVideo(ignored:* = null):void
            {
                if(video)
                {
                    if( (0 == video.videoHeight)
                     || (0 == video.videoWidth)
                    )
                    {
                        video.height = videoDisplay.height;
                        video.width = videoDisplay.width;
                        video.x = 0;
                        video.y = 0;
                    }
                    else
                    {
                        var videoAspect:Number = Number(video.videoWidth) / Number(video.videoHeight);
                        var displayAspect:Number = Number(videoDisplay.width) / Number(videoDisplay.height);
                        var adjustFactor:Number;

                        if(videoAspect >= displayAspect) // video is wider than display
                        {
                            adjustFactor = Number(video.videoWidth) / Number(videoDisplay.width);
                            video.width = videoDisplay.width;
                            video.height = int(Number(video.videoHeight) / adjustFactor);
                            video.x = 0;
                            video.y = int((videoDisplay.height - video.height) / 2);
                        }
                        else
                        {
                            adjustFactor = Number(video.videoHeight) / Number(videoDisplay.height);
                            video.height = videoDisplay.height;
                            video.width = int(Number(video.videoWidth) / adjustFactor);
                            video.x = int((videoDisplay.width - video.width) / 2);
                            video.y = 0;
                        }
                    }
                }
            }

            public function onPlayStatus(info:Object):void {}
            public function onMetaData(info:Object):void {}
            public function onCuePoint(info:Object):void {}
            public function onTextData(info:Object):void {}

            public function ValidateConnectAllowed(isConnected:Boolean, groupNameText:String):Boolean
            {
                return (!isConnected) && (groupNameText.length > 0);
            }
	 }
}
広告

操作

Information

2 responses

22 12 2011
苦学生

初めまして。
現在ピアアシストネットワークを勉強しているのですが、
私も同じくローカルでは接続できましたが、
グローバルでは接続できない状態で困っています。

ピアアシストネットワークのグローバルの件で、ご教授頂ければ幸いです。

16 01 2012
ぱそ

コメント、ありがとうございます。

私も色々と勉強中の身なので、調べて把握できている範囲でお伝えします。

あのあとも色々実験をしていたのですが、
ネットワーク上にNAPTを通さないノードが一つ以上必要だった気がします。

PC-NAPT-インターネット-NAPT-PCという接続は不可能で
PC-インターネット-NAPT-PCや
PC-インターネット-PCという構図なら接続できました。

もしそのピアアシストネットワークにそういったNAPT等のポート変換を行っていないようなノードが1台でもあれば(これがサーバのイメージ)、
グローバルでもそのPCを介して他の全てのノードと接続可能です。

可能ならば、ルータ等介さずに直接インターネットに接続したPCを用意し、ピアアシストネットワークに参加させてみてください。

私も当時調べた際は、ほとんど情報が無かったので
もし、こうした方法以外で繋ぐことができましたら、是非教えてください。

NAPTを介しても特定のポートで変換を行うと繋がったり、するんですかね。

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中




%d人のブロガーが「いいね」をつけました。