Cleansocks Example: The simple chat server example from the
text, ported to Cleansocks.
/* This is Comer's CNAI chatclient.c example ported to use cleansocks. */
#include <iostream>
#include <stdlib.h>
#include <cleansocks.h>
#include <cleanip.h>
#include <cleanbuf.h>
/*-----------------------------------------------------------------------
*
* Program: chatserver
* Purpose: wait for a connection from a chatclient & allow users to chat
* Usage: chatserver <portnumber>
*
*-----------------------------------------------------------------------
*/
using namespace std;
using namespace cleansocks;
static const int BUFFSIZE = 256;
static const char *INPUT_PROMPT = "Input > ";
static const char *RECEIVED_PROMPT = "Received> ";
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "usage: " << argv[0] << " <portnum>"
<< endl;
exit(1);
}
/* Create the socket and bind it to a local port at any IP address. */
TCPsocket s;
IPport p = atoi(argv[1]);
bind(s, IPendpoint(IPaddress::any(), p));
/* Put the socket into listening mode. */
listen(s);
/* Wait for a connection on the socket. */
cout << "Chat Server Waiting For Connection." << endl;
cleansocks::socket c = accept(s);
cout << "Chat Connection Established." << endl;
/* Note: The compiler declares the unqualified reference to socket to
be ambiguous. I don't know a good way to fix it. */
/* Create a buffered socket for convenience (use of recvln). */
buffered_socket conn(c);
/* Iterate, reading from the client and the local user. */
char buff[BUFFSIZE];
int len;
while((len = recvln(conn, buff, BUFFSIZE)) > 0) {
/* Write the data received. */
cout << RECEIVED_PROMPT;
cout.write(buff, len);
/* Send a line to the chatclient */
cout << INPUT_PROMPT;
string loctext;
if(!getline(cin, loctext)) break;
loctext += "\n";
send(conn, loctext);
}
/* Iteration ends when EOF found on stdin or chat connection */
close(c);
cout << "\nChat Connection Closed." << endl;
}