Ns2简单无线网络模拟实验
如果你尝试了很久都没有运行这个实验的话,建议直接复制粘贴以下代码。因为,好像这个好像跟代码的格式,缩进有关(可能跟python有点像)。直接复制粘贴吧,不然会搞到怀疑人生。
#============================================================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 2 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 100 ;# X dimension of the topography
set val(y) 100 ;# Y dimension of the topography
#============================================================================
set ns [new Simulator]
set tracefd [open wireless.tr w]
$ns trace-all $tracefd
set namtracefd [open wireless.nam w]
#设置无线坐标范围
$ns namtrace-all-wireless $namtracefd $val(x) $val(y)
proc finish {} {
global ns tracefd namtracefd
$ns flush-trace
close $tracefd
close $namtracefd
exec nam wireless.nam &
exit 0
}
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace OFF \
-macTrace OFF
for {set i 0} {$i < $val(nn) } {incr i} {
set node_($i) [$ns node]
$node_($i) random-motion 0
}
#设置节点 0 与 节点 1 的初始坐标
$node_(0) set X_ 5.0
$node_(0) set Y_ 2.0
$node_(0) set Z_ 0.0
$node_(1) set X_ 39.0
$node_(1) set Y_ 38.0
$node_(1) set Z_ 0.0
#在50.0s时 节点1 向坐标(25.0,20.0)以速度2.0/s移动
$ns at 50.0 "$node_(1) setdest 25.0 20.0 2.0"
#在10.0s时 节点0 向坐标(20.0,18.0)以速度1.0/s移动
$ns at 10.0 "$node_(0) setdest 20.0 18.0 1.0"
#在100.0s时 节点1 向坐标(49.0,48.0)以速度2.0/s移动
$ns at 100.0 "$node_(1) setdest 49.0 48.0 2.0"
#创建TCP协议节点 和 SINK 协议节点
set tcp [new Agent/TCP]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node_(0) $tcp
$ns attach-agent $node_(1) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"
#在150.0s时重新初始化节点node_0 和节点 node_1 的坐标位置
for {set i 0} {$i < $val(nn) } {incr i} {
$ns at 150.0 "$node_($i) reset";
}
$ns at 150.0 "finish"
$ns run
运行结果如下,是一个动态的演示:(一脸懵逼是什么感受?就是如下感受)