1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <iostream>
#include <bobcat/serversocket>
#include <bobcat/ifdstream>
#include <bobcat/ofdstream>
#include <bobcat/a2x>
using namespace std;
using namespace FBB;
int main(int argc, char **argv)
try
{
if (argc == 1)
{
cerr << "Provide server port number\n";
return 1;
}
size_t portnr = A2x(argv[1]);
ServerSocket server(portnr);
cerr << "server listens on port " << argv[1] << endl;
cerr << "serversocket returns:\n" <<
"address = " << server.dottedDecimalAddress() << endl <<
"port = " << server.port() << endl;
int fd = server.socket(); // open the socket's descriptor
cout << "File descriptor of the socket is " << fd << endl <<
"The server terminates when it receives a single `q' on a line\n"
"A connection is terminated when no input is received anymore.\n"
"Then another connection is possible" << endl;
server.listen(); // listen in blocking mode
while (true)
{
SocketBase fdb = server.accept();
int fd = fdb.socket();
cerr << "Client FD = " << fd << ", " << endl <<
"address = " << fdb.dottedDecimalAddress() << ", " <<
endl <<
"communication through port " << fdb.port() << endl;
IFdStream in(fd); // stream to read from client
OFdStream out(fd); // stream to write to client
string cmd;
while (getline(in, cmd))
{
cout << "Got: " << cmd << endl;
out << "Got: " << cmd << "\r" << endl;
if (cmd[0] == 'q')
return 0;
}
cout << "Ready for another connection\n";
}
}
catch (Errno const &err)
{
cerr <<
err.what() << endl <<
"Server socket on port " << argv[1] <<
" can't be opened" << endl;
return -1;
}
|