链接:http://blog.chinaunix.net/u3/105477/showart_2088091.html
关注点:
#============================================
# 对NS2入门实例3的深入研究
# 通过采样测量应用CBR和FTP的吞吐量、丢包率、时延
#============================================
# 代码注释请参考NS2入门实例3
set ns [new Simulator]
$ns color 1 Blue
$ns color 2 Red
set nf [open out.nam w]
$ns namtrace-all $nf
set nd [open out.tr w]
$ns trace-all $nd
#用于记录采样结果的文件
set f0 [open cbr-throughput.tr w]
set f1 [open cbr-loss.tr w]
set f2 [open ftp-throughput.tr w]
set last_ack 0
#采样过程的代码编写
proc record {} {
global ns null tcp f0 f1 f2 last_ack
set time 0.5 ;#Set Sampling Time to 0.5 Sec
set a [$null set bytes_] ;# CBR/UDP--Through
set b [$null set nlost_] ;# CBR/UDP--Loss
set c [$tcp set ack_] ;# FTP/TCP--Through
set d [$tcp set packetSize_]
set now [$ns now]
# Record Bit Rate in Trace Files, CBR--Throughput
puts $f0 "$now [expr $a*8/$time]"
# Record Packet Loss Rate in File,CBR--loss
puts $f1 "$now [expr $b/$time]"
if { $c >0} {
set e [expr $c - $last_ack]
puts $f2 "$now [expr $e*$d*8/$time]"
set last_ack $c ;#注意哦:更新last_ack, 以便用于进行下一时刻的采样计算
} else {
puts $f2 "$now 0"
}
# Reset Variables
$null set bytes_ 0
$null set nlost_ 0
$ns at [expr $now+$time] "record" ;# Schedule Record after $time interval sec
}
proc finish {} {
global ns nf nd f0 f1 f2
$ns flush-trace
close $nf
close $nd
close $f0
close $f1
close $f2
# Plot Recorded Statistics
exec xgraph cbr-throughput.tr ftp-throughput.tr -geometry 800x400 &
exec xgraph cbr-loss.tr -geometry 800x400 &
exec nam out.nam &
exit 0
}
set s1 [$ns node]
set s2 [$ns node]
set r [$ns node]
set d [$ns node]
$ns duplex-link $s1 $r 2Mb 10ms DropTail
$ns duplex-link $s2 $r 2Mb 10ms DropTail
$ns duplex-link $r $d 1.7Mb 20ms DropTail
$ns queue-limit $r $d 10
$ns duplex-link-op $s1 $r orient right-down
$ns duplex-link-op $s2 $r orient right-up
$ns duplex-link-op $r $d orient right
$ns duplex-link-op $r $d queuePos 0.5
#设置FTP/TCP的部分
set tcp [new Agent/TCP]
$ns attach-agent $s1 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $d $sink
$ns connect $tcp $sink
$tcp set fid_ 1
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#设置CBR/UDP的部分
set udp [new Agent/UDP]
$ns attach-agent $s2 $udp
set null [new Agent/LossMonitor]
$ns attach-agent $d $null
$ns connect $udp $null
$udp set fid_ 2
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false
#模拟时间的设定
$ns at 0.0 "record"
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"
#此行代码可有可无,暂时不管啊!
$ns at 4.5 "$ns detach-agent $s1 $tcp ; $ns detach-agent $d $sink"
$ns run