echod.cpp

Implements an echo server (you can test it with "telnet localhost echo"). It simply echo back every character you send (notice your telnet client may do line buffering).

00001 #include <iostream>
00002 #include <iomanip>
00003 #include <socklibpp/socklistener.h>
00004 
00005 #include <csignal>
00006 
00007 using namespace std;
00008 using namespace socklibpp;
00009 
00010 listener<> connections;
00011 
00012 bool send_back(sock sb, int)
00013 {
00014         char buffer[256];
00015         int r = sb.recv(buffer, sizeof buffer);
00016         if (r<1) {
00017                 sb.close();
00018                 return true;   // remove it from the listener
00019         }
00020         if (sb.send(buffer, r) < r) {
00021                 sb.close();
00022                 return true;
00023         }
00024         return false;
00025 }
00026 
00027 int main()
00028 {
00029         addr_in local(addr_in::addr_any, 0);
00030         local.port("echo");
00031 
00032         sock server;
00033         server.create(sock::pf_inet, sock::sock_stream);
00034 
00035         if (!server.bind(local)) {
00036                 cerr << "Could not bind: " << server.error << endl;
00037                 return 1;
00038         }
00039         if (!server.listen()) {
00040                 cerr << "Could not listen: " << server.error << endl;
00041                 return 1;
00042         }
00043 
00044         cout << "Running echo server on " << local << endl;
00045 
00046         while (1) {
00047                 long s = 10;
00048                 long u = 0;
00049                 if (server.wait_read(u, s)) {
00050                         connections.add(server.accept());
00051                 }
00052 
00053                 connections.for_each_read(send_back);
00054         }
00055 }

Generated on Thu Jan 18 19:26:34 2007 for socklib++ by  doxygen 1.5.1