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

本文介绍如何使用NS2模拟器构建一个简单的网络仿真场景,包括设置拓扑结构、建立节点间的连接、配置数据发送代理及接收代理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个仿真实例:

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

#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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值