官网教程:OMNet++基础案例
打开软件找到tictoc的文件夹打开可以看到里面的所有代码
tictoc1
节点:tic toc
1.创建项目
2.添加NED文件(网络说明文件)
在源文件中输入代码
simple Txc1//设置节点
{
gates:
input in;//节点输入门
output out;//节点输出门
}
//
// Two instances (tic and toc) of Txc1 connected both ways.
// Tic and toc will pass messages to one another.
//
network Tictoc1//网络名称
{
submodules://设置两个子模块
tic: Txc1;
toc: Txc1;
connections:
tic.out --> { delay = 100ms; } --> toc.in;//tic输出门延时100ms之后到达toc的输入门
tic.in <-- { delay = 100ms; } <-- toc.out;//toc输出门延时100ms之后到达tic的输入门
}
写完源文件之后就可以查看我们的网络图
3.加入C++文件
写TXC1节点的功能
新建文件
编写代码
#include <string.h>
#include <omnetpp.h>
using namespace omnetpp;
/**
* Derive the Txc1 class from cSimpleModule. In the Tictoc1 network,
* both the `tic' and `toc' modules are Txc1 objects, created by OMNeT++
* at the beginning of the simulation.
*/
class Txc1 : public cSimpleModule//Txc1是cSimpleModule的子类
{
protected://重新定义两个算法
// The following redefined virtual function holds the algorithm.
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
};
// The module class needs to be registered with OMNeT++
Define_Module(Txc1);
void Txc1::initialize()//Txc1的初始化执行
{
// Initialize is called at the beginning of the simulation.
// To bootstrap the tic-toc-tic-toc process, one of the modules needs
// to send the first message. Let this be `tic'.
// Am I Tic or Toc?
if (strcmp("tic", getName()) == 0) {//如果输入的信息是tic就执行以下代码
// create and send first message on gate "out". "tictocMsg" is an
// arbitrary string which will be the name of the message object.
cMessage *msg = new cMessage("tictocMsg");//创造一个消息对象
send(msg, "out");//从输出门发送消息对象
}
}
void Txc1::handleMessage(cMessage *msg)//每次消息到达时都会执行handleMessage函数
{
// The handleMessage() method is called whenever a message arrives
// at the module. Here, we just send it to the other module, through
// gate `out'. Because both `tic' and `toc' does the same, the message
// will bounce between the two.
send(msg, "out"); // send out the message当接收到消息时就将msg再次发送出去
}
所以上述代码就是初始化时,让tic首先发送一条消息tictocMsg,toc接受到消息之后会返回一条消息tictocMsg
4 添加omnetpp.ini
为了能够运行模拟器,我们需要创建omnetpp.ini文件,omnetpp.ini 告诉仿真程序的网络,你要模拟 (作为NED文件可能包含的几个网络),可以通过参数 该模型,明确指定的种子,随机数发生器,等等。
创建omnetpp.ini文件
在源文件中输入我们需要仿真的网络名称
5 运行
运行omnetpp.ini文件,点击绿色的运行按钮
会生成这样一个框
应为我们在c++文件中没有写停止,所以信息会已知在tic和toc中传递,不会停止
6 调试
调试按钮
调试按钮主要是为了调试错误,所以我们先刻意引入一个错误
在txc1中多加一行这一行将会引起错误
错误信息如上图所示
调试窗口如上图所示
调试时在这个地方可以启动日志
运行完可以在results中看到日志