Cleansocks Example: The simple chat client 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: chatclient
* Purpose: contact a chatserver and allow users to chat
* Usage: chatclient <hostname> <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 != 3) {
cerr << "usage: " << argv[0] << " <hostname> <portnum>"
<< endl;
exit(1);
}
/* Get the IP address, and convert the port number. */
IPaddress comp = lookup_host(argv[1]);
IPport port = atoi(argv[2]);
/* Create a socket and connect it to the server. */
TCPsocket c;
connect(c, IPendpoint(comp, port));
/* This is a job for... buffered_socket! That's because the
chat works one line at a time. */
buffered_socket conn(c);
cout << "Chat Connection Established." << endl;
cout << INPUT_PROMPT;
/* Iterate, copying from the console to the server, then from the
server to the console. */
string loctext;
while(getline(cin, loctext)) {
/* Send the line obtained by the loop test. */
loctext += "\n";
send(conn, loctext);
/* Receive and print a line from the chatserver */
char buff[BUFFSIZE];
int len;
if((len = recvln(conn, buff, BUFFSIZE)) == 0) break;
cout << RECEIVED_PROMPT;
cout.write(buff, len);
/* Prompt for next console read. */
cout << INPUT_PROMPT;
}
/* Iteration ends when stdin or the connection indicates EOF */
close(c);
cout << "\nChat Connection Closed." << endl;
}