/* Demonstrates the conn functions.  This example was adapted
 * from the channel example.  */

#include <stdio.h>
#include <string.h>
#include <libnet.h>

/* Use the driver of your choice.
 * e.g. NET_DRIVER_WSOCK_WIN under Windows.  */
#define DRIVER	NET_DRIVER_SOCKETS

int main (int argc, char *argv[])
{
    NET_CONN *listen;
    NET_CONN *conn;
    int server = 0;
    char buf[256];
    
    /* Search command-line arguments for a "-s" option.  If
     * found then we will run as the server, otherwise as the
     * client.  (Not that it makes much difference here).  */
    for (argv++; *argv; argv++)
	if (strcmp (*argv, "-s") == 0)
	    server = 1;

    net_init ();
    net_loadconfig (NULL);
    
    net_detectdrivers (net_drivers_all);
    net_initdrivers (net_drivers_all);

    if (server) {
	/* If we are the server, open a listening conn and wait
	 * for a client.  */
	listen = net_openconn (DRIVER, "");
	if (!listen) {
	    puts ("Error opening conn.");
	    return 1;
	}
	
	if (net_listen (listen) != 0) {
	    puts ("Error making conn listen.");
	    return 1;
	}

	puts ("Awaiting connection...");
	do conn = net_poll_listen (listen);
	while (!conn);

	/* We could keep the listening conn around and connect
	 * to many clients at once, if we wanted to.  */
	net_closeconn (listen);
    }
    else {
	int status;

	/* If we are the client, open a conn and connect to the
	 * server's listening conn.  */
	conn = net_openconn (DRIVER, NULL);
	if (!conn) {
	    puts ("Error opening conn.");
	    return 1;
	}

	puts ("Enter target address:");
	fgets (buf, sizeof buf, stdin);
	buf[strlen (buf) - 1] = 0;   /* strip newline */

	if (net_connect (conn, buf) != 0) {
	    puts ("Error initiating connection.");
	    return 1;
	}
	
	puts ("Connecting...");
	do status = net_poll_connect (conn);
	while (status == 0);

	if (status < 0) {
	    puts ("Error connecting.");
	    return 1;
	}
    }

    puts ("Enter text to send.  Enter `.' to quit.");
    
    while (1) {
	/* Check if the remote side sent us any messages.  */
	while (net_query_rdm (conn))
	    /* If so, receive them and print them out.  */
	    if (net_receive_rdm (conn, buf, sizeof buf) > 0)
		printf ("Received: %s\n", buf);

	/* Let user enter something.  */
	if (!fgets (buf, sizeof buf, stdin))
	    break;
	buf[strlen (buf) - 1] = 0;   /* strip newline */

	/* Quit condition.  */
	if (strcmp (buf, ".") == 0)
	    break;

	/* Send the text if it is not a blank line.  */
	if (buf[0])
	    net_send_rdm (conn, buf, strlen (buf) + 1);
    }

    /* Close the conn.  */
    net_closeconn (conn);

    /* Quit.  */
    return 0;
}
