#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include "sender.h"

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

if ((argc > 2) || ((2 == argc) && (0 == atoi(argv[1]))))
{

cout << "usage: appserver [server_port]" << endl;
cout << "parameters omited" << endl;

}

CSabulSender* sender = new CSabulSender;

//
// Example for set up SABUL options.
// This should be done before open() is called.
//

bool block = false;
sender->setOpt(SBL_BLOCK, &block, sizeof(block));

//
// Open a SABUL sender.
// Notice the try...catch... structure used for exceptions processing
//

int port;
try
{

if (argc > 1)

port = sender->open(atoi(argv[1]));

else

port = sender->open();

}
catch(...)
{

cout << "Failed to Open New Sabul Server. Program Aborted." << endl;
return 0;

}
//
// The receiver should connect to this port number.
// The application should let the receiver know this port number with
// any methods.
// This is like how a TCP client knows the server port.
//
// To uses a fixed well known port, the application can uses a loop
// call of open() + close() until the returned port is what it expects
//

cout << "SABUL sender is ready at port: " << port << endl;

//
// Now waiting for a receiver to connect in.
//

try
{

sender->listen();

}
catch(...)
{

cout << "Failed to Open New Sabul Server. Program Aborted." << endl;
return 0;

}

timeval time1, time2;

char* data;
int size = 7340000;

gettimeofday(&time1, 0);

//
// Send example data block of 7.34MB 1000 times.
//

for (int i = 0; i < 1000; i ++)
{

data = new char[size];
try
{

//
// With non-blocking sending, the system memory will be soon used up
// if the buffer size of sending data is not controlled.
//

while (!(sender->send(data, size)))

usleep(10);


//
// With blocking sending, the application need to release the buffer
//

if (block)

delete [] data;

}
catch(...)
{

cout << "connection broken ...\n";
return 0;

}

}

//
// Wait until all the data has been sent out.
//

while (sender->getCurrBufSize())

usleep(10);

gettimeofday(&time2, 0);
cout << "speed = " << 6000.0 / double(time2.tv_sec - time1.tv_sec + (time2.tv_usec - time1.tv_usec) / 1000000.0) << "Mbits/sec" << endl;

//
// Close the sender.
//

sender->close();

return 1;

}