您的位置:首页 > 其它

ns2相关学习——tcl脚本编写(1)

2017-03-22 13:08 357 查看
新建一个仿真实例:

set ns [new Simulator]
为了让nam文件和trace文件有地方可以依托,我们要打开.nam文件进行写入,并且使用句柄nf

set nf [open out.nam w]
$ns namtrace-all $nf

设置拓扑图

1、设置节点的脚本语言:建了两个节点,叫n0,n1

set n0 [$ns node]
set n1 [$ns node]

2、建立一个链接

$ns duplex-link $n0 $n1 1Mb 10ms DropTail
该行告诉模拟器对象将节点n0和n1用带宽1Megabit的双工链路连接,延迟10ms、DropTail队列

发送数据

1、为了能真正的发送数据,要设置“代理”——n0发送数据的代理和n1接收数据的代理

首先,设置发送数据的代理

#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

脚本创建一个UDP代理并将其附加到节点n0,然后将一个CBR流量生成器附加到UDP代理。数据包大小被设置为500字节,并且每0.005秒发送一个数据包(即每秒200个数据包)。

然后 设置接收数据的代理

set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
以上脚本创建一个Null代理,作为流量接收器并将其附加到节点n1。

为了能互相发送数据,要将两个代理连接起来,使用以下语句:

$ns connect $udp0 $null0
然后,我们要告诉CBR(发送数据的那个)什么时候开始发送,什么时候结束发送

$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
上面语句就是说,在0.5s的时候开始发送,在4.5s的时候结束发送

下面是整个完整的简单的TCL脚本语言:

#Create a simulator object
set ns [new Simulator]

#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

#Create two nodes
set n0 [$ns node]
set n1 [$ns node]

#Create a duplex link between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail

#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
4000

#Create a Null agent (a traffic sink) and attach it to node n1
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0

#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0

#Schedule events for the CBR agent
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"

#Run the simulation
$ns run
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: