Example 2


[ Back to Software Project Homepage ]


Introduction

In this example, the sender sends 30 packets to the receiver with a speed of 1 packet per second.
The main purpose of this example is to show how to use the new PacketHdr class to put some information in the packet header.

Code

sender.cpp
receiver.cpp
#include "common.h"
#include <iostream>
using namespace std;

class Packet;
class Port;
class Address;
class SendingPort;

int main(int argc, const char * argv[])
{

try {
const char* hname = "localhost";
Address * my_addr = new Address(hname, 3000);
Address * dst_addr = new Address(argv[1], (short)(atoi(argv[2])));
SendingPort *my_port = new SendingPort();
my_port->setAddress(my_addr);
my_port->setRemoteAddress(dst_addr);
my_port->init();

Packet * my_packet;
for (int i=0; i< 30; i++)
{
my_packet = new Packet();
my_packet->setPayloadSize(100);
PacketHdr *hdr = my_packet->accessHeader();
hdr->setOctet('A',0);
hdr->setOctet('B',1);
hdr->setIntegerInfo(i,2);
//hdr->setSize(6);
my_port->sendPacket(my_packet);
cout << "packet "<< i << " is sent!" <<endl;
delete my_packet;
sleep(1);
}
} catch (const char *reason ) {
cerr << "Exception:" << reason << endl;
exit(-1);
}

return 0;
}

#include "common.h"
#include <iostream>
using namespace std;

class Packet;
class Port;
class Address;
class ReceiverPort;

int main(int argc, const char * argv[])
{

try {
const char* hname = "localhost";
Address * my_addr = new Address(hname, (short)(atoi(argv[1])));
ReceivingPort *my_port = new ReceivingPort();
my_port->setAddress(my_addr);
my_port->init();
cout << "begin receiving..." <<endl;

Packet *p;
while (1)
{
p = my_port->receivePacket();
/**
* Post-processing received packet
*/

if (p !=NULL)
cout << "receiving a packet of seq num " << p->accessHeader()->getIntegerInfo(2) << endl;

}
} catch (const char *reason ) {
cerr << "Exception:" << reason << endl;
exit(-1);
}

return 0;
}


Test

./receiver 4000
./sender localhost 4000

Code Analysis:

Look into sender.cpp, the following codes:
	 hdr->setOctet('A',0);
hdr->setOctet('B',1);
hdr->setIntegerInfo(i,2);
//hdr->setSize(6);
has forged a simple packet format as:



Note that whenever you set a field, the size of the header will automatically increase as the size of the new field.
So, when the first byte is set as 'A', the size would be 1. After the 2nd byte is set as 'B', the size will be 2. Finally, a field with a 4-bit integer "i" is set, the size is 6.  And Note the code to manually set size is unnecessary in this case.

Tip:  behavior of receivePacket function

receivPacket function will not return until it has really received something. So, the receiver program hangs when it is called to wait for the 31st packet because that packet does not exist and will never arrive in the receiver.