接上一篇RawSocket和 UdpSocket的例子
#include
#include
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/csma-module.h"
#include "ns3/csma-helper.h"
using namespace std;
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("EleventhScriptExample");
//回调函数
static void recvCallback(Ptr sock)
{
Ptr packet = sock->Recv();
cout << "size:" << packet->GetSize() << endl;
}
void send(Ptr sock)
{
sock->Send(Create(500));
NS_LOG_INFO("aaaaaaaaaaa");
NS_LOG_INFO(sock->GetErrno());
}
//Socket:服务端socket,unknownddress:客户端地址
static bool
ConnectionRequest(Ptr Socket,const Address &unknownAddress)
{
NS_LOG_INFO("ConnectionRequest");
NS_LOG_INFO(Socket->GetSocketType());
NS_LOG_INFO(Socket);
NS_LOG_INFO(unknownAddress);
return true;
}
//Socket: 新socket,unknownAddress:客户端地址
static void
NewConnectionCreated(Ptr Socket,const Address &unknownAddress)
{
NS_LOG_INFO("newConnectionCreated");
NS_LOG_INFO(Socket->GetSocketType());
NS_LOG_INFO(Socket);
NS_LOG_INFO(unknownAddress);
//这里新socket需要设置recv回调
rawSocket->SetRecvCallback(MakeCallback(&recvCallback));
}
int main(int argc, char *argv[])
{
LogComponentEnable("EleventhScriptExample",LOG_LEVEL_ALL);
NodeContainer nodes;
nodes.Create(5);
InternetStackHelper stack;
stack.Install(nodes);
CsmaHelper csmaHelper;
NetDeviceContainer csmaNetDevices = csmaHelper.Install(nodes);
csmaHelper.EnablePcap("haha",csmaNetDevices.Get(0),true);
Ipv4AddressHelper addressHelper;
addressHelper.SetBase("192.168.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = addressHelper.Assign(csmaNetDevices);
//server sockets
TypeId tid = TypeId::LookupByName("ns3::TcpSocketFactory");
Ptr server = Socket::CreateSocket(nodes.Get(0), tid);
InetSocketAddress addr = InetSocketAddress(Ipv4Address::GetAny(),10086);
NS_LOG_INFO(addr);
server->Bind(addr);
//注意这里
server->Listen();
NS_LOG_INFO(server);
//注意这里
server->SetAcceptCallback(MakeCallback(&ConnectionRequest),MakeCallback(&NewConnectionCreated));
//client sockets
Ptr client = Socket::CreateSocket(nodes.Get(4), tid);
InetSocketAddress serverAddr = InetSocketAddress(interfaces.GetAddress(0), 10086);
client->Connect(serverAddr);
NS_LOG_INFO(client);
// client->Send(Create(500));
// client->Close();
Simulator::Schedule(Seconds(1),&send,client);
Simulator::Schedule(Seconds(3),&send,client);
Simulator::Schedule(Seconds(5),&send,client);
Simulator::Schedule(Seconds(7),&send,client);
Simulator::Stop(Seconds(9));
Simulator::Run();
Simulator::Destroy();
return 0;
}
这里注意几个地方,tcp的 连接 会产生新 socket,所以这里的 SetAcceptCallback 有点小特殊
0x 27 66 = 10086,所以可以得出,0x c0 01 = 49153,此即客户端端口号
ns3 真复杂。
我的毕设还遥遥无期,我的考研复试还没有看,哎。。。