NS2学习笔记

来源:互联网 发布:新疆网络限制 编辑:程序博客网 时间:2024/05/22 23:58

关于NS2的概念:

1.component: network objects, event scheduler

 

Ns是一个用c++ 编写,以OTcl解释器为前台,面向对象的模拟器。C++适用于具体协议的实现,OTcl适用于模拟配置。

 

正式开始:

NS2两种运行方式,脚本和命令行。在一个Tcl脚本中定义模拟过程后,进入Shell,输入命令ns *.tcl

一个简单的tcl例子,(后面会写如何编写tcl文件的)

#Create a simulator object

set ns [new Simulator]

 

#Define different colors for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

 

#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 NAM trace file

        close $nf

        #Execute NAM on the trace file

        exec nam out.nam &

        exit 0

}

 

#Create four nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

 

#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 10ms DropTail

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

 

#Set Queue Size of link (n2-n3) to 10

$ns queue-limit $n2 $n3 10

 

#Give node position (for NAM)

$ns duplex-link-op $n0 $n2 orient right-down

$ns duplex-link-op $n1 $n2 orient right-up

$ns duplex-link-op $n2 $n3 orient right

 

#Monitor the queue for link (n2-n3). (for NAM)

$ns duplex-link-op $n2 $n3 queuePos 0.5

 

 

#Setup a TCP connection

set tcp [new Agent/TCP]

$tcp set class_ 2

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]

$ns attach-agent $n3 $sink

$ns connect $tcp $sink

$tcp set fid_ 1

 

#Setup a FTP over TCP connection

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

 

 

#Setup a UDP connection

set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n3 $null

$ns connect $udp $null

$udp set fid_ 2

 

#Setup a CBR over UDP connection

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

 

 

#Schedule events for the CBR and FTP agents

$ns at 0.1 "$cbr start"

$ns at 1.0 "$ftp start"

$ns at 4.0 "$ftp stop"

$ns at 4.5 "$cbr stop"

 

#Detach tcp and sink agents (not really necessary)

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

 

#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"

 

#Print CBR packet size and interval

puts "CBR packet size = [$cbr set packet_size_]"

puts "CBR interval = [$cbr set interval_]"

 

#Run the simulation

$ns run

 

书写一个tcl文件,并且在文件中指定某些输出格式的文件,用ns命令运行后,就会输出指定的文件,用于分析模拟的网络情况。比较常用的是NAMtrace

Nam是一个动画演示程序,如同CD player一样。

Trace文件中记录了整个模拟过程中的数据。

Tcl的语法很简单,和c类似,有编程基础的人看看例子应该就会写了。所以重点在如何使用network objectevent scheduler上。

狼狼要睡觉了,明天继续

 

原创粉丝点击