接上一篇RawSocket和 UdpSocket的例子
TcpSocket
#include <iostream>
#include <string>
#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<Socket> sock)
{
Ptr<Packet> packet = sock->Recv();
cout << "size:" << packet->GetSize() << endl;
}
void send(Ptr<Socket> sock)
{
sock->Send(Create<Packet>(500));
NS_LOG_INFO("aaaaaaaaaaa");
NS_LOG_INFO(sock->GetErrno());
}
//Socket:服務端socket,unknownddress:客戶端地址
static bool
ConnectionRequest(Ptr<Socket> 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> 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<Socket> 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<Socket> client = Socket::CreateSocket(nodes.Get(4), tid);
InetSocketAddress serverAddr = InetSocketAddress(interfaces.GetAddress(0), 10086);
client->Connect(serverAddr);
NS_LOG_INFO(client);
// client->Send(Create<Packet>(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 真複雜。
我的畢設還遙遙無期,我的考研複試還沒有看,哎。。。