/*******************************************************************************
        Samples/RCM2200/echo.c
        Z-World, 2001

        A basic server, that when a client connects, echos back to them
        any data that they send.  Choose port to server by #define PORT
        value.  Internet std sez port #7 is echo, port #9 is discard.
        Most telnet programs accept a second arg of which port to use.
        Ie, from a host, try:    telnet 10.10.6.100 9

        Attention: functions sock_wait_established() and sock_wait_read()
        are really macros.  In case of error, they "goto sock_err;"  Z-World
        wants to remove these macros, so try to avoid their use.

        TELNET port runs in line mode, any other port number is binary xfer.

*******************************************************************************/

#define MY_IP_ADDRESS "10.10.6.100"
#define MY_NETMASK "255.255.255.0"
#define MY_GATEWAY "10.10.6.1"

#memmap xmem
#use "dcrtcp.lib"

/*  Port #7 is ECHO, port #23 is TELNET */
#define IPPORT_TELNET	23
#define IPPORT_ECHO		7
#define IPPORT_DISCARD  9

#define PORT	(IPPORT_TELNET)


tcp_Socket echosock;

main()
{
	char buffer[2048];
	int status;
	int  len;
	
	sock_init();

	while(1) {
		tcp_listen(&echosock,PORT,0,0,NULL,0);
		sock_wait_established(&echosock,0,NULL,&status);
	
		printf("Receiving incoming connection, port %d\n", PORT);
		if( PORT == IPPORT_TELNET ) {
			/**  Always handle TELNET_PORT in ASCII mode.  **/
			sock_mode(&echosock,TCP_MODE_ASCII);
		
			while(tcp_tick(&echosock)) {
				sock_wait_input(&echosock,0,NULL,&status);
				if(sock_gets(&echosock,buffer,2048-1))
					sock_puts(&echosock,buffer);
			}
		} else {
			/**  Other ports are BINARY xfers.  **/
			sock_mode(&echosock,TCP_MODE_BINARY);
			while(tcp_tick(&echosock)) {
				sock_wait_input(&echosock,0,NULL,&status);
				if((len=sock_fastread(&echosock,buffer,2048)) > 0) {
					if( PORT != IPPORT_DISCARD ) {
						sock_flushnext(&echosock);  		/* Hint to set the PSH flag */
						sock_write(&echosock,buffer,len);
					}
				}
			}   /* while socket still open.. */
		}

		/* These services stay open as long as the client holds it.
		 *  Therefore, closing isn't really necessary.
		 *  XXX - is this needed before calling tcp_listen() again?
		 */
//		sock_close(&echosock);
		
sock_err:
		switch(status) {
			case 1: /* foreign host closed */
				printf("User closed session\n");
				break;
				
			case -1: /* timeout */
				printf("\nConnection timed out\n");
				break;
		}
	}
}