Example 1

[ Back to Software Project homepage ]


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_first_packet = new Packet(); my_first_packet->fillPayload(10,"this is just a test"); my_port->sendPacket(my_first_packet);
cout << "packet is sent!" <<endl; } 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 = my_port->receivePacket();
/**
* Post-processing received packet
*/
cout << "receiving a packet:" << endl;
cout << p->getPayload() << endl; } catch (const char *reason ) { cerr << "Exception:" << reason << endl; exit(-1); }

return 0; }

The above code configures the ports with addresses and then initialize them. After that, a packet is sent from one port to another.

Command-Line arguments

The Sender program takes two arguments, destination hostname and destination port number.
The Rreceiver program takes only one argument, local port number of the receiving port.

To have a communication link, the sending port's destination port number must match the receiving port's local port number.

Compile

g++ common.cpp sender.cpp -o sender
g++ common.cpp receiver.cpp
or use the Makefile
make clean
make
After compilation, you will find two new programs "sender" and "receiver" in current directory.

Test

./receiver 4000
./sender localhost 4000

Tip: How to set up communication links by configuring ports

Each port (sending port and receiving port) could have two addresses. One is the local address, the other is the remote address. The remote address corresponds to the local address of the "port" at the other end of communication link.

To configure a sending port, both addresses need to be configured. But to configure a receiving port, only the local address is necessary. Because it is as long as sending port configure the destination correctly, the receiving port could remains "dumb" and needn't to be aware of the remote addresses.

In the above example, we have successfully set up a simplex (not duplex) link from the sending port to the receiving port. Note that the reverse link does not exist!