NS2入門學習(二)之tcl指令碼示例
阿新 • • 發佈:2019-01-28
1、示例分析
tcl語法與python相差不多,以《NS與網路模擬》中的第一個tcl指令碼為例,學習如下:
#建立一個Simulator物件的例項並把它賦值給變數ns set ns [new Simulator] #開啟一個名為linktrace.tr的檔案,用來記錄模擬過程的trace資料,變數nf指向該檔案 set nf [open linktrace.tr w] $ns trace-all $nf #開啟一個名為namtrace.nam的檔案,用來記錄nam的trace資料,變數namtracefd指向該檔案 set namtracefd [open linktrace.nam w] $ns namtrace-all $namtracefd #Define a 'finish' procedure #建立一個名為finish的過程,用來關閉兩個trace檔案,並呼叫nam程式 proc finish {} { global ns nf namtracefd $ns flush-trace #Close the NAM trace file close $nf close $namtracefd #Execute NAM on the trace file exec nam linktrace.nam & exit 0 } #Create four nodes 建立2個節點並分別賦值給n0和n1 set n0 [$ns node] set n1 [$ns node] #Create links between the nodes ,設定頻寬為1Mbit/s,延時為10ms,佇列型別為DropTail $ns duplex-link $n0 $n1 1Mb 10ms DropTail #建立一個UDP Agent並把它繫結到n0上 set udp0 [new Agent/UDP] $ns attach-agent $n0 $udp0 #Setup a CBR over UDP connection,CBR的流量發生器,設定分組大小為500Bytes,傳送間隔為#5ms,然後把它繫結到udp0上 #有一條固定的傳輸速率的聯機(Constant Bit Rate,CBR), #CBR應用程式是架構在UDP之上,因此必需在n0使用UDP agent來產生”udp”用來發送UDP封包,在n1上使用Null agent來產生”sink”以接收由n1傳送過來的UDP封包, #然後把接收的封包釋放。 set cbr0 [new Application/Traffic/CBR] $cbr0 set packet_size_ 500 $cbr0 set interval_ 0.005 $cbr0 attach-agent $udp0 #新建一個Null Agent並把它繫結到n1上,Null是一種資料接收器 set null0 [new Agent/Null] $ns attach-agent $n1 $null0 #將udp0和null0兩個Agent連線起來 $ns connect $udp0 $null0 #告知Simulator物件在0.5s時啟動cbr0(開始傳送資料),在4.5s時停止cbr0(停止傳送資料) #Schedule events for the CBR and FTP agents $ns at 0.5 "$cbr0 start" $ns at 4.5 "$cbr0 stop" #告知Simulator物件在5s時呼叫finish過程 $ns at 5.0 "finish" #開始模擬 $ns run
所以發現問題是在命名tr與nam檔案時,名稱需要相同:linktrace.tr linktrace.nam(nam,這是給NAM用的,用來把模擬的過程用視覺化的方式呈現出來,這可以讓使用者用”看”的方式去了解封包傳送是如何從來源端送到接收端)
2、執行之後可以檢視到nam模擬過程,如下圖
3、在wxjtest.tcl相同目錄下回會看到生成的linktrace.tr和linktrace.nam,接下來需要利用awk工具來分析資料並利用圖形工具生成圖形。