#include <clib/socket_protos.h>
#include <pragmas/socket_pragmas.h>
#include <clib/rtgextra_protos.h>
#include <pragmas/rtgextra_pragmas.h>
#include <clib/exec_protos.h>
#include <pragmas/exec_pragmas.h>
#include <stdio.h>
#include <netdb.h>
#include <rtgmaster/rtgtcpip.h>
#define UDPDemo 1

// If you want to compile this demo to use
// TCP instead of UDP, set UDPDemo to 0

struct Library *SocketBase=0;
struct Library *RTGExtraBase=0;

void main()
{
 if (RTGExtraBase=OpenLibrary("rtgextra.library",0))
 {
  if (SocketBase=OpenLibrary("bsdsocket.library",0))
  {
   struct RTG_Socket *rs;
   struct RTG_Socket *msgsock;
   char buf[1024];
   int rval;
   long mode=1;

#ifndef UDPDemo
   rs=OpenServer(SocketBase,3056,SOCK_STREAM,0);
#else
   rs=OpenServer(SocketBase,3056,SOCK_DGRAM,0);
#endif

   //RtgIoctl(SocketBase,rs,&mode);

   while(1)
   {

#ifndef UDPDemo
    msgsock=RtgAccept(SocketBase,rs);
#else
    msgsock=rs;
#endif

    do {
        struct sockaddr_in *si;

// Note : As GetUDPName returns 0 for TCP connections, this code
// works for TCP *and* UDP ...

// If you want a Connection with Multiple Client, WITHOUT
// using RunServer (works only with UDP...) you can simply
// open multiple Clients and then test, from which Client a
// Message came using RtgInAdr (it can't differentiate
// between multiple Clients running on the same machine, BTW).

        si=GetUDPName(SocketBase,msgsock);
        rval=RtgRecv(SocketBase,msgsock,buf,si,1024);

#ifndef UDPDemo

#else
        if (rval>0) printf("Message from : %s\n",RtgInAdr(SocketBase,si));
#endif

        if (rval>0) RtgSend(SocketBase,msgsock,buf,si,rval);
       } while (rval>0);

#ifndef UDPDemo
    CloseClient(SocketBase,msgsock);
#endif

   }
   if (SocketBase) CloseLibrary(SocketBase);
   if (RTGExtraBase) CloseLibrary(RTGExtraBase);
  }
 }
}
 
