1、头文件
2、ns3命名空间 using namespace ns3;
3、日志
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
4、主函数
int main(int argc,char *argv[])
{
......
}
5、生成网络节点
NodeContainer nodes;
nodes.create(2);//创建两个节点
6、物理连接计算机(节点)
实际中物理连接两台计算机成为网络一般来说需要使用网卡和网线,ns-3中将对应的物理实体抽象为网络设备和信道2个概念,下面的语句就实现了网络节点物理连接:
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
当调用了pointToPoint.Install(nodes)后,会有2个节点,每一个节点安装了点到点网络设备,在它们之间是一个点到点信道。2个设备会被配置在个有2ms传输延时的信道上以5Mbit/s的速率传输数据。
7、为计算及安装协议栈
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
8、安装应用层
下面的代码用来安装服务器端应用程序、设置端口号:
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
应用对象需要一个时间参数来“开始”产生数据通信并且可能在一个可选的时间点“停止”。我们提供了开始和停止的2个参数,时间点是用 ApplicationContainer的方法Start和Stop 来设置的,这些方法以“Time”对象为参数。在这种情况下,使用了一种明确的C++转换序列来获得C++双精度(double)的1.0并且用一个Seconds转换来把它转换到ns-3的Time对象。
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
这两行会使echo服务应用在1s时开始(生效)并在10s时停止(失效)。既然已经声明了一个模拟事件(就是应用的停止事件)在10s时被执行,模拟至少会持续10s。
设置客户端应用层:
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);//创建了一个助手并告诉它设置客户端的远端地址为服务器节点的IP地址。同样告诉它准备发送第二个数据分组到端口9。
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
“MaxPackets”属性告诉客户端所允许它在模拟期间能发送的最大数据分组个数。“Interval”属性告诉客户端在2个数据分组之间要等待多长时间,而“PacketSize属性告诉客户端它的数据分组应该承载多少数据。本例中让客户端发送一个1024byte的数据分组。正如echo服务端一样,告诉echo客户端何时来开始和停止,但是这里本文使客户端在服务端生效1s后才开始(在模拟器中时间2S的时候)
9、启动和关闭模拟器
Simulator::Run ();
Simulator::Destroy ();
return 0;